ApiaryActiveLive
Try: pause · settings · learn · wipe
← Community / Reading Room
DA
craft · 27 min read

Design a Small Automation with a Stop Condition: Finish the Current Item, Record the Rest

A small automation, such as a script that drafts forty articles, converts a folder of documents or uploads a batch of files, needs a defined end. "When the…

A clean stop is one that someone else can resume without guessing. That takes three things decided before the run starts: what ends it, what happens to the item in flight, and what gets written down.

AI disclosure. This longread was drafted by AI (Claude, from an earlier Grok Bot draft) for Apiary. It has not been reviewed or verified by the founder. Sources were opened and read on 26 November 2026; provider documentation changes often, so dated limits are marked. Worked examples are hypothetical.

A small automation, such as a script that drafts forty articles, converts a folder of documents or uploads a batch of files, needs a defined end. "When the list is empty" is one end. A real job also needs others: a spending cap, a deadline, a run of identical errors, a person pressing stop, or the platform it runs on deciding the time is up. If those ends are not designed, they still happen, but they happen as crashes, and a crash leaves no record of what was finished.

A clean stop means that after the job ends, anyone can tell exactly what was done, what was not, and how to continue without redoing or skipping anything. In practice, that comes down to five moves:

  1. Stop starting new items as soon as a stop condition is met.
  2. Finish or safely abandon the item in progress. Do not leave half-written files where a reader or the next run will treat them as finished.
  3. Record every item's status (done, failed, unknown, not started), with evidence.
  4. Write the reason for stopping and a resume point.
  5. Exit with an honest status: "partial" or "stopped," not "success."

This page expands an earlier Apiary guide of the same name. That guide's advice still stands: choose explicit limits, freeze the input set, keep completion, intentional stop, failure and unknown outcome as distinct statuses, and make resumption possible. What it lacked was evidence about how the platforms that run jobs actually stop them, the fact that partial work is generally not rolled back, the difference between limits that mean "wait" and limits that mean "stop," and a concrete stop record. Those are added below, with sources.

1. Why "it will just finish" is not a stop condition

A loop that processes a list has an implicit stop condition: it ends when the list runs out. That covers only the happy path. The earlier version of this guide named three ways a bounded task turns into an unbounded one: a failed item that is retried forever, an input set that keeps growing while the job runs, and repeated retries that never give up. Each needs its own explicit rule.

There is a fourth reason that is easy to forget. Even a job that would eventually finish does not get to decide when it stops. The platform it runs on has its own limits. Almost every runner, whether a container platform, a CI service, a serverless function or a plain shell command with a timeout, will at some point send the job a polite request to stop and then, if the job does not comply, kill it outright. Sections 3 to 6 document what those requests look like on common platforms. The practical point is that a job designer has to plan for two kinds of stop: the ones the job decides for itself, and the ones imposed on it from outside.

Editorial suggestion: write the stop conditions down before the first run, in the same place as the job's configuration. A stop condition that exists only in the author's head is not available to the person who has to restart the job at 2 a.m.

2. The stop conditions to define up front

The table below lists the conditions that most small batch jobs should handle, with a suggested clean response for each. The responses are editorial suggestions, drawn from the documented behaviors in later sections; the right choice for a particular job depends on whether its items are independent and what a wrong result would cost.

ConditionWhat it usually meansClean response (editorial suggestion)
Input list exhaustedThe intended work is doneVerify results, write the record, exit "complete" only if every item succeeded
Spend or quota cap reachedFurther requests will fail until a person actsStop at once; record "cap reached" with the time; do not retry
Rate limit with a stated waitCapacity will return shortlyWait as instructed, within a total time budget; this is not a stop by itself
Non-retryable error on one item (validation, bad input)That item cannot succeed as configuredMark the item failed; continue only if items are independent
Same error on several items in a rowSomething systemic is wrongStop the run; the cause is probably not in the items
Unknown outcome (timeout after sending)The write may or may not have happenedMark the item "unknown"; check the target before any retry
Cancel signal from the platform or a personSomeone outside wants the job to endStop starting items; finish or abandon the current one within the grace window; write the record
Deadline or runtime budget reachedThe job has used its allotted timeSame as a cancel: finish the current item, record a resume point
Item attempt limit reachedRetries on this item are not workingMark the item failed with the last error; apply the run's failure rules
New inputs appear mid-runThe scope is changingDefer them to a later batch unless the plan explicitly includes them

Two of these deserve emphasis because they are the ones most often handled badly. The spend-cap case is covered in section 8: some limits look like rate limits but will never clear on their own. The repeated-error case is covered in section 9: a job that marks forty items failed one at a time, for the same reason, has wasted forty attempts and made the record harder to read.

3. How platforms stop a job: Kubernetes

Kubernetes is a useful reference because its documentation describes the stop sequence in detail. When a Pod is deleted, "the kubelet attempts graceful shutdown. Typically, with this graceful termination of the pod, kubelet makes requests to the container runtime to attempt to stop the containers in the pod by first sending a TERM (aka. SIGTERM) signal, with a grace period timeout, to the main process in each container. Once the grace period has expired, the KILL signal is sent to any remaining processes, and the Pod is then deleted from the API Server" (Kubernetes, Pod Lifecycle). The same page states the default: "A Pod is granted a term to terminate gracefully, which defaults to 30 seconds" (documented behavior, as of 26 November 2026).

The page also documents a case where even that window is skipped. When a container's exit matches a rule with the RestartAllContainers action, the Pod is restarted in place, and under "Fast Termination" the documentation says "the configured terminationGracePeriodSeconds is not respected, and any configured preStop hooks are not executed" (Kubernetes, Pod Lifecycle). The lesson for a job designer is that a grace window is a courtesy that depends on configuration, not a guarantee.

Kubernetes Jobs, the resource intended for batch work, add their own stop conditions, and they are worth reading as a design checklist even if you never run Kubernetes (Kubernetes, Jobs, documented behavior as of 26 November 2026):

  • A retry limit. "The .spec.backoffLimit is set by default to 6," and "Failed Pods associated with the Job are recreated by the Job controller with an exponential back-off delay (10s, 20s, 40s ...) capped at ten minutes." The page footer records a 12 October 2026 edit that replaced "six minutes" with "ten minutes," which is itself a reminder to date any limit you copy from documentation.
  • A deadline that beats the retry limit. "Once a Job reaches activeDeadlineSeconds, all of its running Pods are terminated and the Job status will become type: Failed with reason: DeadlineExceeded." The page adds that the deadline "takes precedence over its .spec.backoffLimit," so a Job that is still retrying "will not deploy additional Pods once it reaches the time limit."
  • A failure budget across items. For Indexed Jobs, where each index is a separate unit of work, "When the number of failed indexes exceeds the maxFailedIndexes field, the Job controller triggers termination of all remaining running Pods for that Job." The documentation notes that "The Job gets marked as failed even if some, potentially nearly all, of the indexes were processed successfully." That sentence is the strongest argument in this page for per-item records: a top-level "Failed" can sit on top of mostly finished work.
  • A rule for errors that should stop everything at once. A Pod failure policy can map a specific exit code to the FailJob action, so that an error known to be a bug ends the Job instead of consuming its retries. The documented example uses exit code 42 "simulating a bug which triggers the FailJob action."

Each of these maps directly to a small script: an attempt limit per item, a total deadline, a cap on failed items, and a list of errors that end the run immediately.

4. How platforms stop a job: Docker, a shell timeout and the signals underneath

Docker documents the same polite-then-forceful pattern. For docker container stop, "The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL." The timeout flag "sets the number of seconds to wait for the container to stop," and "If the container does not exit after the timeout elapses, it's forcibly killed with a SIGKILL signal." If no default is configured, the daemon's default "is 10 seconds for Linux containers, and 30 seconds for Windows containers." Setting the timeout to -1 means "the daemon waits indefinitely for the container to exit" (Docker, docker container stop, documented behavior as of 26 November 2026).

A plain shell job can impose the same discipline on itself with GNU timeout. Its manual says it sends "the default 'TERM' signal" on timeout unless another is chosen, and that --kill-after will "Ensure the monitored command is killed by also sending a 'KILL' signal," with the extra duration counted "from the point in time when timeout sends the initial signal." Its exit status is documented too: "124 if command times out" and "137 if command or timeout is sent the KILL(9) signal (128+9)" (GNU Coreutils manual, timeout invocation). Those two numbers are useful in a wrapper script: they let the record say "stopped by our own deadline" rather than a bare "exit code 124."

Why does every platform send two signals? Because the second cannot be negotiated with. The Linux manual page for signals states that "The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored" (Linux man-pages, signal(7)). A job can react to SIGTERM by saving its state. It cannot react to SIGKILL at all. Whatever the job has not written down when the second signal arrives is lost.

Proposed explanation: the gap between the two signals is the only time a job has to perform a clean stop when the stop is imposed from outside. Docker's Linux default of 10 seconds and Kubernetes' default of 30 seconds are both short compared with a single slow API call. A job therefore cannot plan to "finish the batch" when it receives SIGTERM. At most it can finish, or abandon, one item and write its record.

5. How platforms stop a job: CI runners and serverless functions

Hosted services impose time limits that the job may not even see coming.

GitHub Actions (documented behavior as of 26 November 2026). jobs.<job_id>.timeout-minutes is "The maximum number of minutes to let a job run before GitHub automatically cancels it. Default: 360." Step-level timeout-minutes is "The maximum number of minutes to run the step before killing the process," with "Maximum: 360 for both GitHub-hosted and self-hosted runners." Two other settings change what "failure" means. continue-on-error "Prevents a job from failing when a step fails," and the concurrency setting cancel-in-progress: true will "also cancel any currently running job or workflow in the same concurrency group" when a new one is queued (GitHub Docs, Workflow syntax for GitHub Actions). The last one matters for batch jobs: pushing a new commit can cancel a half-finished publishing run, and the run that replaces it has to know where the cancelled one stopped. The same page notes that for bash and sh, "fail-fast behavior is enforced using set -e," so a failing command ends the step unless the script handles it.

AWS Lambda (vendor documentation, as of 26 November 2026). "Timeout is the maximum amount of time in seconds that a Lambda function can run. The default value for this setting is 3 seconds, but you can adjust this in increments of 1 second up to a maximum value of 1,800 seconds (30 minutes)." The page also warns that "When another service invokes your function synchronously, that service might stop waiting for a response before your function times out" (AWS Lambda Developer Guide, Configure Lambda Event Function timeout). That warning describes a second kind of stop: the caller gives up while the work continues. From the caller's side, the item's outcome is unknown.

Editorial suggestion: look up the time limit of whatever runs your job, write it beside the job's own deadline, and set the job's deadline comfortably below it. A job that stops itself at 50 minutes on a 60-minute runner gets to write its record. A job that is killed at 60 minutes does not.

6. Handling the stop signal inside the job

Receiving SIGTERM gracefully is a programming task, and the details depend on the language. Python is a common choice for small automations, and its documentation includes several facts that shape how a handler should work (Python documentation, signal, Python 3.15 documentation as fetched 26 November 2026):

  • Handlers run later than you might expect. "A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point (for example, at the next bytecode instruction)."
  • Some work cannot be interrupted. "A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received."
  • Only the main thread runs handlers. "Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread," and "only the main thread of the main interpreter is allowed to set a new signal handler."
  • Ctrl-C is already wired up. By default, SIGINT "is translated into a KeyboardInterrupt exception if the parent process has not changed it."
  • Locks inside handlers are dangerous. The documentation warns that "Synchronization primitives such as threading.Lock should not be used within signal handlers. Doing so can lead to unexpected deadlocks."

Taken together, these suggest a simple and robust pattern (editorial suggestion): the signal handler does almost nothing except set a "stop requested" flag. The main loop checks the flag before starting each new item. When the flag is set, the loop stops picking up items, lets the current one reach a safe point or abandons it, and then writes the stop record. The handler never tries to write files or call APIs itself.

The same Python notes explain why a job should be built around short steps. If one item involves a single blocking call that takes four minutes, no handler will run during those four minutes, and a 30-second grace window will expire long before the loop sees the flag. Breaking work into steps that each finish well inside the grace window, and checking the flag between them, is what makes a graceful stop possible at all.

7. Partial work is not rolled back

When a multi-step job stops, the steps that already finished stay finished. Most tools do not undo them. Terraform's documentation states this plainly: "Your infrastructure may be in an invalid state after a Terraform apply operation fails. Terraform does not automatically roll back a partially-completed apply. After you resolve the error, you must apply your configuration again to update your infrastructure to the desired state" (HashiCorp, terraform apply command reference, documented behavior as of 26 November 2026).

A batch of uploads, emails or published pages behaves the same way. If 86 articles went live before the stop, they are live. Proposed explanation: rollback requires the job to know how to reverse each kind of effect, and many effects (a sent email, a notification, a search engine fetching a page) cannot be reversed at all. So the realistic goal of a clean stop is not "undo everything." It is "describe exactly what was done," so a person can decide whether to continue, roll back by hand, or leave things as they are. A separate rollback note, written before the batch runs, covers the cases where undoing is possible.

There is one place where a job can and should avoid partial results: the single item in progress. A file that is half written at the moment of a SIGKILL is the worst kind of partial result, because it looks like a finished file. Python's os.replace documentation describes the standard defense. It renames a file over another, and "If successful, the renaming will be an atomic operation (this is a POSIX requirement)," though "The operation may fail if src and dst are on different filesystems" (Python documentation, os). Editorial suggestion: write each output to a temporary file in the same directory, then rename it into place only when it is complete. A reader, or the next run, then sees either the old file or the complete new one, never a fragment. Leftover temporary files become a known, easily cleaned category in the stop record.

8. Limits that mean "wait" and limits that mean "stop"

Many API errors look alike but call for opposite responses. A rate limit says "slow down"; a spending cap says "stop until a person acts." Treating the second as the first produces a job that sleeps and retries until its deadline, then reports a confusing timeout instead of the real cause.

Anthropic's rate-limit documentation draws the line explicitly (vendor documentation, as of 26 November 2026). For ordinary rate limits, "If you exceed any of the rate limits, you get a 429 error describing which rate limit was exceeded. When the response has a retry-after header, wait that many seconds before retrying." For the spend cap, "Once you reach your tier's spend cap, API usage pauses until 00:00 UTC on the first day of the next month, unless you request a higher limit sooner." The response is still a 429 with error type rate_limit_error, "the same as for a rate limit, but the response has no retry-after header. Retrying, including the SDK's automatic retries, fails until access resumes." The page names the field to check: "On the Messages API, error.details.error_code is enforced_spend_limit_reached. Use it to tell this response apart from a rate limit" (Anthropic, Rate limits).

OpenAI's error documentation makes the same distinction for billing errors: "Retrying billing, spend, or quota errors won't restore API access. Update the relevant credits or limits before sending another request" (OpenAI, Error codes, vendor documentation as of 26 November 2026).

The design consequence (editorial suggestion): the job's error classifier should have three outcomes, not two. "Retry after a wait" for rate limits with a stated delay, "fail this item" for item-specific errors, and "stop the run" for account-level conditions like spend caps, revoked keys or exhausted quotas. The third outcome should be checked by a specific field, such as the error code above, not by guessing from the HTTP status, because the status is the same in both cases.

9. Retry limits, failure budgets and the repeated-error stop

Unbounded retrying is the opposite of a clean stop. Google's Site Reliability Engineering book is direct about it: "Limit retries per request. Don't retry a given request indefinitely. Consider having a server-wide retry budget. For example, only allow 60 retries per minute in a process, and if the retry budget is exceeded, don't retry; just fail the request" (Ulrich, "Addressing Cascading Failures," Site Reliability Engineering, Google). The "60 per minute" figure is offered as an example, not a recommended value.

For a batch job, that idea extends naturally from requests to items. Three layers of limit work together (editorial suggestion, modeled on the Kubernetes Job controls in section 3):

  1. Per-attempt timeout: how long one call may take before it counts as failed or unknown.
  2. Per-item attempt limit: how many times one item may be tried before it is marked failed.
  3. Per-run failure budget: how many items may fail before the whole run stops.

The third layer catches the systemic failure. If an API key has expired, every item will fail for the same reason. Without a run-level budget, the job marks every item failed one at a time, spends its whole time budget doing so, and leaves a record with a hundred identical errors. With a rule such as "stop after three consecutive items fail with the same error class," the job stops early, the record says why, and the remaining items are correctly listed as "not started" rather than "failed."

Microsoft's Circuit Breaker pattern describes the same mechanism for calls to a remote service. In the Closed state, the proxy "maintains a count of the number of recent failures," and "If the number of recent failures exceeds a specified threshold within a given time period, the proxy is placed into the Open state." While Open, "The request from the application fails immediately and an exception is returned to the application," and after a timer expires, in the Half-Open state, "A limited number of requests from the application are allowed to pass through and invoke the operation" (Microsoft, Circuit Breaker pattern, Azure Architecture Center). A small batch job rarely needs the Half-Open state; for a run that a person will restart, "open the breaker and stop" is usually enough.

10. Unknown outcomes need their own status

A timeout after a request was sent does not mean the request failed. The server may have finished the work and the response was lost. The AWS Lambda warning in section 5, that a synchronous caller "might stop waiting for a response before your function times out," is one documented source of this situation. The safe record for such an item is "unknown," with a note saying what to check.

Unknown items change how a resume works. Before the next run touches them, it should look at the target: does the file exist, does the page carry the new text, is there a record with the expected ID? Only then can the item be moved to "done" or "not started." Retrying an unknown item blindly risks a duplicate, such as two copies of the same article or the same email sent twice. Idempotency keys (see the related reading on idempotency) reduce that risk where the target supports them, but the record should still distinguish "we know this failed" from "we don't know what happened."

11. What the stop record contains

The stop record is the product of a clean stop. It should be written by the job itself, at the end of every run, whatever the reason for ending. The fields below are an editorial suggestion; the structure matters more than the format, which can be JSON, YAML or a simple table.

FieldWhat it holdsWhy
Run IDA unique identifier for this runLets later runs and people refer to it
Started at / stopped atTimestamps with time zoneTimes without zones cause confusion across machines
Stop reasonOne of a fixed list: complete, cap reached, deadline, cancelled, failure budget exceeded, crashedA fixed list can be counted and searched
Stop detailThe triggering error code or signal"enforced_spend_limit_reached" is more useful than "429"
Input setThe frozen list of items, or a reference to itShows what the run was authorized to do
Per-item statusdone / failed / unknown / skipped / not started, with evidenceThe core of the record
TotalsCounts per status that add up to the input totalA quick check that nothing is missing
Resume pointThe next not-started item, plus unknown items to check firstTells the next run where to begin
Partial artifactsTemporary files, drafts, locks, and whether they were cleaned upPrevents half-files being mistaken for results
Resume commandExact command and settings, including idempotency keysAvoids a resume that differs from the original run
Exit statusThe process exit code and its meaningLets a scheduler or CI system react correctly

The totals line is a cheap integrity check. If the input had 120 items and the per-status counts add to 119, the job lost track of one, and that is worth knowing before anyone trusts the record.

12. Writing the record so it survives the stop

A record that is written only at the very end is lost if the job is killed. Two habits make records survive (editorial suggestions):

  • Append as you go. Write each item's status to the log as soon as it is known, rather than holding everything in memory for a final summary. If the process is killed, the log still shows every finished item.
  • Write the summary atomically. Write the final summary to a temporary file and rename it into place, using the same technique described in section 7, so the summary is either the old version or the complete new one.

The per-item log and the summary then serve different purposes. The log is the evidence; the summary is the index. If they disagree, the log wins, and the next run should rebuild the summary from it.

Editorial suggestion: the stop handler's first action, after setting the stop flag, should be to make sure the record of the current item can be written. If the grace window is short, the record is more valuable than the last item's output.

13. Exit honestly

Schedulers, CI systems and people read the exit status before they read anything else. A job that stops partway through and exits with code 0 tells all of them that everything worked.

The documented exit conventions give a starting point. GNU timeout returns "124 if command times out" and 137 for a KILL signal (GNU Coreutils manual). Kubernetes marks a Job that hits its deadline as "type: Failed with reason: DeadlineExceeded" (Kubernetes, Jobs), and the reason field carries the information that the bare failure does not.

Editorial suggestion: reserve exit code 0 for "every item in the frozen input set succeeded and was verified." Use distinct non-zero codes for "stopped partway, record written" and for "crashed, record may be incomplete," and document them beside the job. A GitHub Actions setting like continue-on-error, which "Prevents a job from failing when a step fails" (GitHub Docs), should be used only when someone has decided that a failure in that step genuinely does not matter, because it turns a red result into a green one.

14. Worked example: a drafting run that hits a spend cap (hypothetical)

Hypothetical example. A job is authorized to draft 120 articles from a frozen list. It calls a model API once per article, writes each draft to a temporary file, and renames it into the output folder when complete. Its stop rules are: stop immediately on an account-level error; mark an item failed after three attempts; stop the run after three consecutive items fail with the same error class; and stop itself at 50 minutes on a runner with a 60-minute limit.

At item 87, the API returns a 429. The job's classifier checks the error code field rather than the status, finds the documented spend-cap code, and classifies it as "stop the run." It does not retry. Item 87 has no output; its temporary file is empty and is deleted. The job writes:

run: draft-2026-11-26-a
stopped_at: 2026-11-26T14:12:09Z
stop_reason: cap_reached
stop_detail: enforced_spend_limit_reached (HTTP 429, no retry-after)
totals: 120 = 86 done + 1 failed + 0 unknown + 33 not_started
failed: item-087 (cap reached before generation)
resume_point: item-087
partial_artifacts: none (tmp file for item-087 removed)
exit: 3 (stopped, record complete)

When the budget is raised, the next run reads the record, starts at item 87, and processes the remaining 34 items. Nothing is duplicated and nothing is skipped.

Hypothetical variant. Suppose the same job instead treated every 429 as a rate limit. It would sleep, retry, sleep and retry until its 50-minute deadline, then stop with reason "deadline." The record would be accurate about counts but wrong about the cause, and the person reading it would look for a performance problem that does not exist.

15. Worked example: a cancel in the middle of an upload (hypothetical)

Hypothetical example. A CI workflow uploads 40 converted documents. Halfway through, a teammate pushes a fix and the workflow's concurrency group has cancel-in-progress: true, so the running job is cancelled (the documented behavior in section 5). The job receives a termination signal.

The handler sets the stop flag. Item 21 is mid-upload. The upload call returns successfully a few seconds later, inside the grace window, so the job records item 21 as done with the returned file ID. The loop sees the flag and does not start item 22. The job writes the record (20 earlier done, item 21 done, items 22 to 40 not started) and exits with its "stopped" code.

Now change one detail: the upload of item 21 is still waiting for a response when the grace window ends, and the runner sends the kill signal. The per-item log already shows items 1 to 20 as done, because they were appended as they finished. Item 21 has no entry. The next run, reading the log, should treat item 21 as unknown, check the destination for it, and only then decide whether to upload it again. That is the difference between a clean stop and an abrupt one: in the abrupt case, the record is still useful, but one item needs a check.

16. A pre-run checklist

Before a small automation's first real run, the following questions should have written answers (editorial suggestion):

  1. What is the frozen input set, and where is it stored?
  2. What happens to items that arrive during the run?
  3. What is the per-attempt timeout, per-item attempt limit and per-run failure budget?
  4. Which errors stop the whole run immediately, and which field identifies them?
  5. What is the job's own deadline, and what is the runner's hard limit?
  6. How long is the runner's grace window between the polite and forceful signals, and does every step finish well inside it?
  7. Does the job write outputs atomically (temporary file, then rename)?
  8. Does it append each item's status as soon as it is known?
  9. What exit codes does it use, and does code 0 mean "every item verified"?
  10. Can a second person resume the job from the record alone, without asking the author?

If the answer to the last question is no, the job's stop condition is not yet designed.

17. What the evidence does and does not show

It shows that common platforms stop jobs with a polite signal followed, after a short documented window, by a forceful one that cannot be handled. It shows that the windows are short (10 or 30 seconds by default on the platforms checked) and configurable, and that at least one Kubernetes path skips the window entirely. It shows that tools such as Terraform do not roll back partial work, that some AI providers document spend caps that return the same status code as rate limits but will not clear on retry, and that experienced operators recommend bounding retries at both the request and the process level.

It does not show a correct set of numbers for any particular job. The defaults quoted here (30 seconds, 10 seconds, six retries, 360 minutes, 1,800 seconds) are documented values as of 26 November 2026; they change, as the Kubernetes Jobs page's own October 2026 correction shows. The stop record, the three-way error classifier and the failure budget are editorial suggestions built from those documented behaviors, not standards. No study cited here measures how often batch jobs are stopped uncleanly or what that costs; the case for designing the stop rests on the documented mechanics, not on incident statistics.

Related reading on Apiary

  • guide-create-a-rollback-note-before-publishing-a-content-batch
  • how-to-record-partial-success-across-files
  • request-failure-vs-unknown-execution-outcome
  • rate-limit-vs-spending-or-daily-limit
  • biggie-idempotency-in-apis

Sources

Last checked: 2026-11-26.

  1. Kubernetes Authors. "Pod Lifecycle." Kubernetes documentation. https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/ - TERM then KILL sequence, 30-second default grace period, in-place restart skipping the grace period.
  2. Kubernetes Authors. "Jobs." Kubernetes documentation, last modified 12 October 2026. https://kubernetes.io/docs/concepts/workloads/controllers/job/ - backoffLimit default 6, back-off delays capped at ten minutes, activeDeadlineSeconds precedence, maxFailedIndexes, FailJob pod failure policy.
  3. Docker Inc. "docker container stop." Docker documentation. https://docs.docker.com/reference/cli/docker/container/stop/ - SIGTERM then SIGKILL, 10-second Linux and 30-second Windows defaults, -1 waits indefinitely.
  4. Free Software Foundation. "timeout invocation." GNU Coreutils manual (9.12). https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html - default TERM signal, --kill-after, exit statuses 124 and 137.
  5. Linux man-pages project. "signal(7)." https://man7.org/linux/man-pages/man7/signal.7.html - SIGKILL and SIGSTOP cannot be caught, blocked or ignored.
  6. Python Software Foundation. "signal: Set handlers for asynchronous events." Python 3 documentation. https://docs.python.org/3/library/signal.html - deferred execution of handlers, uninterruptible C calls, main-thread rule, SIGINT default, lock warning.
  7. Python Software Foundation. "os: Miscellaneous operating system interfaces." Python 3 documentation. https://docs.python.org/3/library/os.html - os.replace atomic rename and same-filesystem caveat.
  8. GitHub. "Workflow syntax for GitHub Actions." GitHub Docs. https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax - job timeout default 360 minutes, step timeout maximum, continue-on-error, cancel-in-progress, set -e default.
  9. Amazon Web Services. "Configure Lambda Event Function timeout." AWS Lambda Developer Guide. https://docs.aws.amazon.com/lambda/latest/dg/configuration-timeout.html - 3-second default, 1,800-second maximum, synchronous callers that stop waiting.
  10. HashiCorp. "terraform apply command reference." Terraform documentation. https://developer.hashicorp.com/terraform/cli/commands/apply - no automatic rollback of a partially completed apply.
  11. Anthropic. "Rate limits." Claude Platform documentation. https://platform.claude.com/docs/en/api/rate-limits - 429 with retry-after for rate limits, spend cap pause to 00:00 UTC on the first of the month, no retry-after, enforced_spend_limit_reached code.
  12. OpenAI. "Error codes." OpenAI API documentation. https://developers.openai.com/api/docs/guides/error-codes - retrying billing, spend or quota errors does not restore access.
  13. Ulrich, M. "Addressing Cascading Failures," ch. 22 in Site Reliability Engineering (Google). https://sre.google/sre-book/addressing-cascading-failures/ - limit retries per request, server-wide retry budget example.
  14. Microsoft. "Circuit Breaker pattern." Azure Architecture Center. https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker - Closed, Open and Half-Open states and failure thresholds.
Frequently asked
What is Design a Small Automation with a Stop Condition: Finish the Current Item, Record the Rest about?
A small automation, such as a script that drafts forty articles, converts a folder of documents or uploads a batch of files, needs a defined end. "When the…
What should you know about 1. Why "it will just finish" is not a stop condition?
A loop that processes a list has an implicit stop condition: it ends when the list runs out. That covers only the happy path. The earlier version of this guide named three ways a bounded task turns into an unbounded one: a failed item that is retried forever, an input set that keeps growing while the job runs, and…
What should you know about 2. The stop conditions to define up front?
The table below lists the conditions that most small batch jobs should handle, with a suggested clean response for each. The responses are editorial suggestions, drawn from the documented behaviors in later sections; the right choice for a particular job depends on whether its items are independent and what a wrong…
What should you know about 3. How platforms stop a job: Kubernetes?
Kubernetes is a useful reference because its documentation describes the stop sequence in detail. When a Pod is deleted, "the kubelet attempts graceful shutdown. Typically, with this graceful termination of the pod, kubelet makes requests to the container runtime to attempt to stop the containers in the pod by first…
What should you know about 4. How platforms stop a job: Docker, a shell timeout and the signals underneath?
Docker documents the same polite-then-forceful pattern. For docker container stop , "The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL." The timeout flag "sets the number of seconds to wait for the container to stop," and "If the container does not exit after the timeout…
References & sources
  1. Apiary Reading Room — Open, cited knowledge base — funded to keep bee & practical research free.
From the Apiary Reading Room. Opinion & editorial — not financial advice. We don't overclaim.
More from the Reading Room