<p>Due to a memory leak in one of our services I am planning to add a k8s CronJob to schedule a periodic restart of the leaking service. Right now we do not have the resources to look into the mem leak properly, so we need a temporary solution to quickly minimize the issues caused by the leak. It will be a rolling restart, as outlined here:</p>
<p><a href="https://stackoverflow.com/questions/52422300/how-to-schedule-pods-restart">How to schedule pods restart</a></p>
<p>I have already tested this in our test cluster, and it seems to work as expected. The service has 2 replicas in test, and 3 in production.</p>
<p>My plan is to schedule the CronJob to run every 2 hours.</p>
<p>I am now wondering: How will the new CronJob behave if it should happen to execute while a service upgrade is already running? We do rolling upgrades to achieve zero downtime, and we sometimes roll out upgrades several times a day. I don't want to limit the people who deploy upgrades by saying &quot;please ensure you never deploy near to 08:00, 10:00, 12:00 etc&quot;. That will never work in the long term.</p>
<p>And vice versa, I am also wondering what will happen if an upgrade is started while the CronJob is already running and the pods are restarting.</p>
<p>Does kubernetes have something built-in to handle this kind of conflict?</p>

Henrik Söderlund
<p><a href="https://stackoverflow.com/questions/52422300/how-to-schedule-pods-restart">This answer to the linked question</a> recommends using <code>kubectl rollout restart</code> from a CronJob pod.  That command internally works by adding an annotation to the deployment's pod spec; since the pod spec is different, it triggers a new rolling upgrade of the deployment.</p>
<p>Say you're running an ordinary redeployment; that will change the <code>image:</code> setting in the pod spec.  At about the same time, the <code>kubectl rollout restart</code> happens that changes an annotation setting in the pod spec.  The Kubernetes API forces these two changes to be serialized, so the final deployment object will always have both changes in it.</p>
<p>This question then reduces to &quot;what happens if a deployment changes and needs to trigger a redeployment, while a redeployment is already running?&quot;  The <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rollover-aka-multiple-updates-in-flight" rel="nofollow noreferrer">Deployment documentation</a> covers this case: it will start deploying new pods on the newest version of the pod spec and treat all older ones as &quot;old&quot;, so a pod with the intermediate state might only exist for a couple of minutes before getting replaced.</p>
<p>In short: this should work consistently and you shouldn't need to take any special precautions.</p>
