Quick revision
The short answer
We store each command as a database row with its type, a JSON payload, a status, an attempt count, a next run time and an idempotency key, in the same transaction as the business change that creates it. Workers claim due rows with SELECT ... FOR UPDATE SKIP LOCKED or a lease column that expires, look up a handler by type in a registry, and run it; because at-least-once execution is unavoidable, handlers are idempotent. Failures are retried with exponential backoff until a maximum, then moved to a dead-letter status, payloads are versioned so old commands still parse after a deployment, and before building any of this we check whether an existing library such as JobRunr, db-scheduler or Quartz already covers our needs.
What to remember
In this answer, we designed a durable command queue in a database table with type, JSON payload, status, attempts, next run time and an idempotency key. Workers claim rows with FOR UPDATE SKIP LOCKED and a lease, a registry maps types to idempotent handlers because at-least-once execution cannot be avoided, failures are retried with backoff until they become dead letters, and versioned payloads keep old commands readable. Before building, we compare with existing libraries like JobRunr, db-scheduler and Quartz.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We store each command as a database row with its type, a JSON payload, a status, an attempt count, a next run time and an idempotency key, in the same transaction as the business change that creates it. Workers claim due rows with SELECT ... FOR UPDATE SKIP LOCKED or a lease column that expires, look up a handler by type in a registry, and run it; because at-least-once execution is unavoidable, handlers are idempotent. Failures are retried with exponential backoff until a maximum, then moved to a dead-letter status, payloads are versioned so old commands still parse after a deployment, and before building any of this we check whether an existing library such as JobRunr, db-scheduler or Quartz already covers our needs.
Why this question is asked
Background jobs look simple until the first restart in the middle of a batch, the first duplicate charge, or the first deployment that cannot read yesterday's queued jobs. A database-backed command queue is popular because it needs no new infrastructure and can be written in the same transaction as the data that triggers it. Interviewers ask this design question to see whether we know how to claim work safely between workers, what delivery guarantee is really possible, and how the system behaves over months of deployments. In this answer, we will design the table, the claiming query, the handler registry, retries and dead letters, payload versioning, and finally weigh building it against using a library.
1The Command Table
Each command is one row. The type says which handler runs it, the payload holds the command's data as JSON, and the rest of the columns describe its progress. The idempotency key lets producers avoid enqueuing the same command twice and lets handlers detect a repeat. Because the row lives in the same database as the business data, the service that places an order can insert the order and its send-invoice command in one transaction, so a command exists if and only if the change that caused it committed.
2Claiming Work Safely
Several workers, possibly in several instances of the service, poll the same table. The danger is two workers picking the same row. PostgreSQL and MySQL 8 support SELECT ... FOR UPDATE SKIP LOCKED: the query locks the rows it returns and skips rows another transaction has already locked, instead of waiting for them. So each worker gets a different batch, with no blocking.
10 messages in order. Play them, or step through them one at a time.
Notice that we mark the rows RUNNING with a lease, locked_until, and commit immediately, rather than holding the row lock while the handler runs. Holding a database transaction open for a handler that calls an email provider for 30 seconds would tie up connections and locks. The lease is the safety net: if a worker crashes, its rows stay RUNNING, and a sweeper resets rows whose locked_until has passed back to PENDING so another worker picks them up. The lease must be longer than the slowest normal handler, or a slow but healthy job will be run twice.
3The Handler Registry and Idempotency
A registry maps each command type to a handler. In Spring, handlers are beans implementing one interface, and the registry builds a map from type to handler at startup, failing on duplicates, just as with any strategy registry. The worker reads the payload, gives it to the handler, and on success marks the row DONE.
The idempotency check is not optional. A worker can finish the handler and crash before it marks the row DONE, or its lease can expire while it is still running. In both cases the command runs again. No design based on a database and external side effects can avoid this; at-least-once execution is the honest guarantee. So handlers must make a repeat harmless, by checking a record of completed keys, by using upserts, or by passing the key to external APIs that deduplicate.
4Retries, Backoff and Dead Letters
When a handler throws, the worker records the error, sets the row back to PENDING and pushes next_run_at into the future with exponential backoff, for example 30 seconds times 2 to the power of attempts, with some random jitter so that many failed jobs do not all retry at the same instant. After a maximum number of attempts, say 8, which with that formula spans about two hours, the row moves to DEAD instead.
DEAD rows are not deleted. They are the dead-letter queue: a dashboard lists them with their last error, an alert fires when their count rises, and an operator can fix the cause and reset them to PENDING. Some errors should go straight to DEAD without retries, such as a payload that fails validation, because retrying will never help.
- PENDING, duenext_run_at <= now
- Claimed by a workerRUNNING, lease 5 minutes
- Did the handler succeed?Exceptions recorded in last_errorYesDONENoCheck attempts
- Attempts below the maximum?8 in this designYesPENDING with backoff and jitterNoDEAD, alert, manual review
- Lease expired while RUNNING?Worker crashedYesSweeper resets to PENDINGNoLeave it running
5 steps in order. Play them, or step through them one at a time.
5Versioning Payloads Across Deployments
Commands can wait for hours in the queue, and a deployment may happen in between. If the new code changes the payload class, renaming orderId to orderNumber, the new worker must still read rows written by the old producer, and during a rolling deployment old workers may read rows written by new producers. So each row stores payload_version. Handlers accept the versions they know, converting old versions to the current shape, and we follow the usual rule for compatible changes: add optional fields freely, never rename or remove a field in place, and introduce a new version with an upcaster when the shape must change. Old version support is removed only after the queue has no rows with that version.
6Build or Use a Library
Everything above is real work, plus monitoring, an admin view, scheduling of recurring jobs and cleanup of old DONE rows. Libraries exist for database-backed jobs in Java: JobRunr, db-scheduler and Quartz with its JDBC job store are common choices, and Spring Batch covers large batch processing. They have solved claiming, retries and dashboards, and been tested by many users. So we build our own only when needs are special, such as tight integration with our transaction and outbox model, or constraints a library cannot meet, and we compare the libraries' guarantees, licences and operational fit against the list in this design before deciding. Check each library's current version for the exact features it offers.
7Follow-up questions
Why not use Kafka or a message broker instead of a table?
A broker is better for high throughput and for many consumers across services. The table wins when volumes are moderate, when we want the command created in the same transaction as the business data without an outbox, and when we need to query, reschedule or inspect individual jobs. Many systems use both: a table for commands inside a service, Kafka for events between services.
What happens if a handler is slower than the lease?
The sweeper thinks the worker died and another worker runs the same command, which idempotency makes harmless but wasteful. We set the lease above the slowest expected run, let long handlers extend their lease periodically as a heartbeat, and alert on commands that run near the lease limit.
How do you keep the table from growing forever?
A cleanup job deletes or archives DONE rows older than a retention period, such as 30 days, and the partial index on PENDING rows keeps polling fast regardless of table size. For high volumes, partitioning the table by creation date makes cleanup a cheap partition drop.
8Conclusion
In this answer, we designed a durable command queue in a database table with type, JSON payload, status, attempts, next run time and an idempotency key. Workers claim rows with FOR UPDATE SKIP LOCKED and a lease, a registry maps types to idempotent handlers because at-least-once execution cannot be avoided, failures are retried with backoff until they become dead letters, and versioned payloads keep old commands readable. Before building, we compare with existing libraries like JobRunr, db-scheduler and Quartz.
Open with
I would store each command as a row in a job table: a type that names the handler, a JSON payload with a payload version, a status, an attempt count, a next run time, a lease column and a unique idempotency key.
Then, if they want more
The nice property of a table is that the service can insert the command in the same transaction as the business change, so the command exists exactly when the change committed. Workers poll for due rows using SELECT FOR UPDATE SKIP LOCKED, which lets several workers each grab a different batch without blocking each other.
In the same short transaction they mark those rows RUNNING with a lease, and commit, so we do not hold locks while handlers run. If a worker dies, a sweeper resets expired leases back to PENDING. A registry maps the type to a handler bean.
Since a worker can crash after doing the work but before marking it done, at-least-once execution is unavoidable, so every handler must be idempotent, for example by recording completed idempotency keys or passing the key to the external API.
On failure, I record the error and reschedule with exponential backoff and jitter, and after a maximum number of attempts the row moves to a DEAD status, which acts as the dead-letter queue with alerts and a way to replay. Because jobs can sit in the queue across deployments, payloads are versioned and handlers read old versions.
Finally, I would check JobRunr, db-scheduler or Quartz first, and only build this if our needs are unusual.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design a background job system where commands are stored in a database and executed by...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/6b4038b622/