<p><strong>Scenario</strong> : A repo of NestJs is executing a cron job for sending messages to subscribers as per cron expression. Scenario is running fine when only one instance is running.</p>
<p><strong>Problem</strong> : Multiple email received by subscriber when <em>multiple</em> instance(pods) are running in K8 cluster.</p>
<p><strong>Solution Looking for</strong> : Without database, or separate out service can we do something with &quot;<strong>K8s</strong>&quot; <em><strong>yaml</strong></em> so that at a given point of time only one pod is executing the cron job.</p>

Pravesh Kumar
<p>You can try the <code>concurrencyPolicy</code> option in <strong>cronjob</strong> on the kubernetes cluster. This option helps to run only one task at a time. Even though multiple triggers are requested for a job, it will skip the triggers until the execution of the current task is done.</p>
<p>In your case you need to set the option to <code>Forbid</code> as shown below, so that it will make sure to execute only request at a time.</p>
<pre><code>apiVersion: batch/v1
kind: CronJob
metadata:
  name: demo
spec:
  schedule: &quot;* * * * *&quot;
  concurrencyPolicy: Forbid    #Enabling the concurrencyPolicy
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: demo
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure
</code></pre>
<p><strong>Note:</strong> Using the <code>concurrencyPolicy</code> field to limit the number of pods might affect the performance of a job, as it may result in longer execution time.</p>
<p>You can also limit the creation of a number of pods by using the <code>parallelism</code> field in the job. For more information refer to this <a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/#parallel-jobs" rel="nofollow noreferrer">parallelism</a>.</p>
<p>For more detailed information refer to this <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#concurrency-policy" rel="nofollow noreferrer">official k8's</a> documentation</p>
