Kubernetes を利用時、大きいデータサイズの画像を複数回POSTするとエラーが出る

Rails を用いて、画像アップロードをするシステムを作っていた時、画像を連続3回アップロードすると502エラーが出る場合があった。

これは、メモリの使用量が大きくなり、pod 内のプロセスがkill されていたことが原因だった。
Ruby on Rails のメモリ消費が大きいというのもあるが、Image Magick を使った画像のリサイズ処理は多少重い処理で、メモリ消費、CPU消費どちらも大きい。

CPUのlimitによって処理が遅くなり、メモリのlimitによってプロセスが終了する。
pod 自体は Terminate されていないように見えたので、原因になかなか気がつかなかった。


ログを見るとこのようになっている。

Memory cgroup out of memory: Kill process 1117697 (bundle) score 1802 or sacrifice child Killed process 1117697 (bundle) total-vm:950788kB, anon-rss:340148kB, file-rss:14348kB, shmem-rss:0kB
[Note] Aborted connection 36967 to db: 'hoge_db' user: 'hoge' host: 'cloudsqlproxy~34.00.100.04' (Got an error reading communication packets)
[error] 7#7: *7447 upstream prematurely closed connection while reading response header from upstream, client: 10.146.15.198, server: _, request: "POST /admin/datas/1/ HTTP/1.1", upstream: "http://10.0.15.103:3000/admin/datas/1/", host: "***.com", referrer: "https://***.com/datas/1/edit/"
Client closed local connection on 10.40.4.24:3306
[error] 7#7: *5400 client intended to send too large body: 2328315 bytes, client: 10.40.4.181, server: _, request: "GET /errors/5xx.html HTTP/1.0", host: "cluster-ip-stg-hoge", referrer: "https://***/datas/1/edit/"

CPU は limit を超えても、killされず処理が遅くなるだけだが、memory は kill されるのは間違えないように。

          resources:
            requests:
              cpu: 50m
              memory: 230Mi
            limits:
              cpu: 500m
              memory: 800Mi