Many automations start life as a single script: pull records from one system, push them into another, send a Slack message, update a spreadsheet. It works for days or weeks, until the first transient API outage, rate limit, or unexpected input shows up.
At that point, the “simple script” becomes a reliability problem: it silently drops work, duplicates updates, or gets stuck halfway through a batch. A full message broker or workflow platform may be overkill, but you still need a queue, visibility, and a way to resume safely.
This post describes an evergreen pattern that fits small teams: using the filesystem as a lightweight queue. It is not fancy, but it is surprisingly effective for automations that run on a server, VM, or container with durable storage.
Why small automations fail in production
Automation failures are rarely caused by “bad code” in the core logic. More often, they come from missing operational features that mature systems take for granted:
- No durable handoff: The script pulls a list of items from an API and starts processing, but if it crashes midway, the remaining items are lost.
- No record of intent: You cannot answer “what exactly were we trying to do?” when a customer reports a mismatch.
- No controlled retries: A temporary 429 or 503 causes a hard failure, or a tight loop hammers the API and makes things worse.
- No idempotency: Retrying causes duplicates, like double-creating tickets or sending the same email twice.
- No isolation: One malformed record blocks the entire batch.
A filesystem-backed queue addresses these with a simple idea: every unit of work becomes a small file that moves through clearly named states.
What the file-based queue pattern is
The file-based queue pattern turns your automation into two conceptual parts:
- Producer: discovers work and writes a “work item” file to disk.
- Worker: claims a work item, processes it, then marks it done or failed.
Instead of “remembering” what to do in memory, your system records work items durably. If the process restarts, it continues from the directory state.
Key Takeaways
- Durability comes from writing work items to disk before you execute side effects.
- Visibility comes from explicit states like
pending,in-progress,done,failed. - Safety comes from idempotency keys and “claiming” work with atomic moves.
- Operability comes from keeping inputs, outputs, and errors attached to each work item.
Designing work items and folder structure
A work item should be self-contained: if you hand the file to someone else, they should understand what the automation attempted. In practice, JSON is common, but any structured format works.
What goes in the payload
Keep the payload focused on intent and traceability. Typical fields include:
- action: the verb, such as
create_contact,update_invoice_status,sync_customer. - source: system name and record IDs, for example
{"system":"billing","invoiceId":"inv_123"}. - target: system name and identifiers if known.
- idempotencyKey: a deterministic string derived from the business identity of the operation (more below).
- attempt: retry count, starting at 0.
- timestamps: when the work was enqueued and last attempted.
Include only what you are comfortable storing on disk. If the work involves sensitive data, store references (IDs) and fetch the details at processing time, or encrypt the payload and manage keys carefully.
A simple, effective folder layout
The queue is a directory with subdirectories representing state. Work moves by renaming or moving files, which is typically atomic on a single filesystem.
queue/
pending/ # new work items, ready to be claimed
in-progress/ # claimed by a worker
done/ # completed successfully (optional retention window)
failed/ # exhausted retries or non-retryable error
dead-letter/ # requires human attention (optional alias of failed)
logs/ # per-item logs or summaries (optional)
Retention matters. Keeping “done” items for a short period (for example, a week) can be invaluable for debugging, as long as it does not accumulate sensitive data or infinite disk usage.
Idempotency keys: your safety net
An idempotency key is a stable identifier for the intended effect of the work. If you retry the same work item, you use the same key, so the target system can reject duplicates or your worker can detect “already done.”
Example: “Create CRM contact for billing customer 8472” could use crm_contact:create:billing_customer:8472. If your script crashes after the API call, the retry should not create a second contact.
Even if the target API does not support idempotency, you can still use the key in your own local “results index” file or database table to record what you already completed.
Processing rules: retries, locks, and visibility
The worker loop is simple: list files in pending, claim one, process it, then move it to done or failed. The operational details are what make it reliable.
Claiming work safely
A common approach is to “claim” a file by moving it from pending to in-progress. This reduces double-processing when two workers run at once. If your platform supports atomic rename within a filesystem, use that to avoid race conditions.
To make debugging easier, include the worker ID in the filename or write a small sidecar metadata file that records which worker claimed it and when.
Retries that do not create chaos
Not all errors are equal. Define a simple retry policy:
- Retryable: rate limits, timeouts, transient 5xx responses. These should requeue with backoff.
- Non-retryable: schema errors, missing required fields, invalid credentials. These should go straight to
failedwith an explanation.
Backoff can be implemented by storing a notBefore timestamp in the payload and skipping items until the time arrives, or by moving to a delayed folder organized by time buckets. Keep it simple, and do not spin in a tight loop.
Handling stuck items
If a worker crashes after claiming an item, it will sit in in-progress. Add a “lease” concept: if in-progress items are older than a threshold, move them back to pending and increment the attempt count. This turns crashes into delays instead of permanent loss.
Real-world example: invoice-to-CRM sync
Consider a small business automation that syncs paid invoices from a billing system into a CRM:
- Producer runs every 10 minutes, queries billing for invoices that became “paid” since the last checkpoint.
- For each invoice, producer writes a work item file describing “mark deal as won” and “update customer lifetime value.”
- Worker processes items one by one, calling the CRM API and recording results.
Here is how the file-based queue helps in concrete failure modes:
- CRM rate limits: worker marks the attempt, sets
notBefore, and requeues. Work slows down instead of failing. - Malformed invoice record: that single work item moves to
failedwith a reason, while the rest continue. - Worker deploy restart: anything in
pendingremains. Anything inin-progressgets reclaimed after the lease expires. - Duplicate invoices from producer bug: idempotency key prevents repeated “mark deal as won” updates from causing inconsistent states.
The biggest operational win is explainability. When someone asks “why is this customer’s CRM value wrong,” you can inspect the exact work item, the attempts, and the error message without reconstructing history from logs.
Common mistakes (and how to avoid them)
- Mixing discovery and execution: If your script fetches 500 records and immediately processes them without writing work items, you lose durability. Fix: always enqueue first, then execute.
- Assuming “move to done” equals “success”: Success means the external side effect happened as intended. Fix: record the external response identifier (ticket ID, contact ID) in the work item or a sidecar result file.
- Unbounded “done” retention: Disk fills up, or old sensitive payloads linger. Fix: implement retention limits and sanitize payloads.
- No consistent idempotency key: A random UUID per attempt defeats the purpose. Fix: derive a key from stable business identifiers.
- Retrying non-retryable errors: This creates noise and wastes API calls. Fix: classify errors, and fail fast on validation and auth issues.
When not to use this pattern
The file-based queue pattern is intentionally lightweight. It is not the right fit for every scenario.
- High throughput or strict ordering requirements: If you need thousands of events per second or hard ordering across many workers, use a purpose-built queue.
- Multiple machines without shared durable storage: If workers run on different hosts and do not share a filesystem, you will struggle with coordination. Use a networked queue or database-backed approach.
- Very sensitive payloads: If storing references is not possible and the payload contains sensitive data, you need stronger security controls than “files in a directory.”
- Complex branching workflows: If one job fans out into many steps with dependencies, a workflow engine may be clearer than ad hoc folder states.
If you are unsure, a good heuristic is: if you can explain the process as “a list of independent work items,” this pattern tends to work well.
Copyable implementation checklist
Use this checklist to implement the pattern without overengineering:
- Define the unit of work (one invoice, one ticket, one row), and keep it as small as practical.
- Design a stable idempotency key based on business identity, not attempt identity.
- Create queue folders:
pending,in-progress,done,failed. - Write before you act: producer writes the work item file first, then worker performs the side effect.
- Claim with an atomic move from
pendingtoin-progress. - Attach trace info: attempt count, last error, external response IDs.
- Implement retries with backoff and a max attempt limit.
- Implement a lease timeout for
in-progressitems to recover from crashes. - Set retention policies for
doneandfailedfolders. - Define an operator routine: how to requeue a failed item, how to inspect and fix root causes, and when to delete.
Conclusion
Reliable automation is less about clever code and more about durable state, safe retries, and debuggability. A file-based queue gives you those properties with tools you already have, as long as you design clear work items, idempotency keys, and simple operational rules.
If your automation is small enough to run on one machine with durable storage, this pattern can be a practical step up from “one script and hope.”
FAQ
How many workers should I run?
Start with one worker until you understand failure modes and rate limits. If you need more throughput, add a second worker and confirm your claiming method prevents double-processing. Only scale up when you can observe and control retries.
Can this run from cron, or does it need a long-running service?
Either works. A long-running worker is simpler for continuous processing, but cron can be fine if each run claims a small number of items and exits. The key is that state lives in the queue folders, not in memory.
What if the queue grows and uses too much disk?
Add retention and compaction: delete old done items after a window, archive failed items after review, and keep payloads minimal. Also track queue depth; a growing pending folder is an operational signal.
Should I use a database instead of files?
If you already have a database and want stronger concurrency controls or multi-host workers, a database-backed queue can be a good next step. Files are a strong option when you want maximum simplicity and strong “inspectability” without adding dependencies.