We are going to design an async job idempotency ledger.
Requirements:
- Natural keys: We want to use natural keys (business keys) to identify a job, but also have a unique idempotency key for each job instance.
- Exactly-once illusion: The system should ensure that the same job (by natural key) is not executed more than once at the same time, and if it is retried, we can recover the result of the previous execution.
- Auditability: We need to keep a history of all job attempts, including their status, timestamps, and any errors.
Design:
We'll have two main tables:
-
jobs table: This table will store the current state of each job by its natural key. It will have one row per natural key (i.e., one active job per natural key at a time) and will be used for fast lookup of the current state.
Columns:
id (UUID or bigserial): primary key for the row in this table (not the natural key).
natural_key (string or appropriate type): the business key that identifies the job. This should be unique.
status (enum: 'pending', 'running', 'completed', 'failed'): current status of the job.
result (JSON or text, nullable): the result of the job if completed.
error (text, nullable): error message if failed.
created_at (timestamp): when the job was first created.
updated_at (timestamp): last update.
We will have a unique constraint on natural_key to ensure only one active job per natural key.
-
job_attempts table: This table will store every attempt of a job, including retries. This provides auditability.
Columns:
id (UUID or bigserial): primary key.
job_id (UUID): foreign key to the jobs table.
attempt_number (integer): the attempt number for this job (starting at 1).
status (enum: same as above): status of this attempt.
result (JSON or text, nullable): result of this attempt.
error (text, nullable): error message if failed.
started_at (timestamp): when the attempt started.
finished_at (timestamp): when the attempt finished (null if still running).
We might also want an index on job_id and attempt_number for quick lookup.
How it works:
When a job is submitted:
-
We generate an idempotency key (which could be a UUID) for the job request. However, note that we are using natural_key for business logic, but we also want to handle multiple requests for the same job.
-
We try to insert a new row in the jobs table with the natural_key. If a row with that natural_key already exists and is not in a terminal state (completed or failed) then we consider the job as already in progress and return the existing job's id or current state.
-
If the row does not exist or is in a terminal state (and we allow retries of failed jobs? This is a design decision), we can create a new job.
However, note that we want to allow retries. So if a job failed, we might want to retry it. But then we have to decide: does a retry create a new job or reuse the existing job?
Let's clarify:
Option 1: Each job (by natural_key) can have multiple attempts, but only one active job at a time. When we retry, we are actually creating a new attempt for the same job.
In this case, the jobs table represents the current state of the job (which is the aggregate of attempts). The job_attempts table records each attempt.
So the flow:
-
First submission for a natural_key: create a job row and an attempt (attempt 1). Status of job is the same as the attempt (pending -> running -> completed/failed).
-
If the job fails and we want to retry: we don't create a new job row (because natural_key already exists) but we create a new attempt for that job. The job's status is updated to the latest attempt's status.
-
If the job is already running (i.e., there's an attempt in progress) then we don't allow a new attempt until the current one finishes? Or do we queue? We have to decide.
We want exactly-once illusion, meaning that from the caller's perspective, the job is executed once and only once. But internally we might have multiple attempts if the first one fails.
However, if the job is already running and we get another request for the same natural_key, we have two options:
a) Reject the request (because the job is already in progress) and return the existing job id.
b) Queue the request and run it after the current one finishes? But then we are effectively allowing multiple attempts for the same job? That breaks exactly-once.
Let's define exactly-once: the job should be executed at most once for a given natural_key at a given point in time. But if it fails, we might retry (so multiple executions, but only one successful). However, the caller might want to know that the job is already running and not submit a new one.
So I think we should:
- If a job is in progress (status 'running' or 'pending') for a natural_key, then we return the existing job and do not create a new attempt. The caller can then wait for the result.
- If the job is in a terminal state (completed or failed) and we allow retries, then we create a new attempt (and update the job's status to pending, then running, etc.). But note: the job row already exists, so we are reusing it.
But wait: what if the job is completed and we don't want to retry? Then we just return the completed job.
So the decision on whether to allow retries is a business rule. We can have a configuration per job type or a parameter in the request.
Let's assume we allow retries only on failed jobs, and only if the request explicitly asks for retry (or maybe automatically after a failure?).
Alternatively, we can think of the job as having a lifecycle:
- When we first create a job, we set its status to 'pending'. Then we start the first attempt.
- If the attempt fails, the job status becomes 'failed'. Then, if a retry is requested (and maybe after a backoff) we create a new attempt.
- We can also have a maximum number of attempts.
So we need:
- In the `jobs` table, we might want to store:
* `max_attempts` (integer, default 3)
* `current_attempt` (integer, starting at 1, increments with each retry)
- In the `job_attempts` table, we have `attempt_number` which should match the job's `current_attempt` for that attempt.
How to handle concurrency:
We must ensure that two requests for the same natural_key don't both create a new job or both start an attempt.
We can use a database transaction with row-level locking.
Steps for submitting a job:
Let natural_key = ?, allow_retry = ? (boolean, default false), max_attempts = ? (optional)
1. Begin transaction.
2. Try to select the job by natural_key for update (SELECT ... FOR UPDATE). This will lock the row.
3. If the job exists:
- If the job is in a terminal state (completed or failed) and allow_retry is true and current_attempt < max_attempts:
* Increment current_attempt in the job.
* Create a new attempt with the new attempt_number and status 'pending'.
* Update the job status to 'pending' (or leave it as the attempt's status? We'll set the job status to the attempt's status when we start the attempt).
- Else (job is running or terminal without retry):
* Return the existing job (and maybe the latest attempt?).
4. If the job does not exist:
* Insert a new job row with:
natural_key, status='pending', current_attempt=1, max_attempts (if provided, else default).
* Insert the first attempt (attempt_number=1, status='pending').
5. Commit.
Then, we have a separate worker that picks up jobs with status 'pending' (or maybe we use a queue) and starts the attempt.
When starting an attempt:
1. Begin transaction.
2. Select the job by id (from the attempt's job_id) for update.
3. Update the attempt's status to 'running' and set started_at.
4. Update the job's status to 'running'.
5. Commit.
When the attempt finishes:
1. Begin transaction.
2. Update the attempt: set status to 'completed' or 'failed', set result or error, set finished_at.
3. Update the job: set status to the same as the attempt, and if completed, set the result (or if failed, set the error?).
But note: we might have multiple attempts, so the job's result/error should be the latest attempt's.
4. Commit.
But wait: what if the job fails and we want to retry? Then the job's status should go back to 'pending'? Actually, when we retry, we create a new attempt and set the job status to 'pending' (in the submission step above). Then the worker will pick it up and set it to 'running'.
Alternatively, we can have the job status always reflect the latest attempt's status. So:
- When we create a new attempt (retry), we set the job's status to the new attempt's status (which is 'pending').
- When the attempt starts, we set both the attempt and the job to 'running'.
- When the attempt finishes, we set both to the final status.
This way, the job status is always the same as the latest attempt's status.
So the job table's status might be redundant? We can get the status from the latest attempt? But we want fast lookup by natural_key without joining.
We can keep the job status as a cached value of the latest attempt's status.
Auditability:
We have the `job_attempts` table that records every attempt.
Exactly-once illusion:
From the caller's perspective, they submit a job and get a job id. They can then query the job by that id (or natural_key) and see the result.
If they submit the same job again (same natural_key) while it's running, they get the same job and see it's running. They don't get a new job.
If the job fails and they retry (with allow_retry=true) then a new attempt is created and the job status goes back to pending, then running, etc. But note: the job id remains the same. So the caller sees the same job id but with a new attempt? They might see the job's status change from failed to pending? That's acceptable.
However, what if the caller doesn't know about the retry? They might have submitted the job, it failed, and then they resubmit without knowing it failed. We have two options:
Option A: If the job is in a terminal state (failed) and they resubmit without allow_retry, we return the same job (with status failed). They can then decide to retry by setting allow_retry.
Option B: We automatically retry? That would be a business rule.
We can leave it to the caller: if they want a retry, they must set allow_retry. Otherwise, they get the existing job (which might be failed).
But note: the natural_key might be for a resource that changes. For example, a job to process a file. If the file changes, then the same natural_key (maybe the file path) might represent a different file? Then we would want a new job. So the natural key must be defined such that it uniquely identifies the job for the same input. If the input changes, the natural key should change.
So the natural key must be a hash of the input? Or a combination of business keys that uniquely identify the job.
Let's assume the natural key is provided by the caller and they are responsible for ensuring that it changes if the job's input changes.
Implementation details:
We'll need:
- An enum for status: ['pending', 'running', 'completed', 'failed']
- The `jobs` table:
CREATE TABLE jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
natural_key VARCHAR(255) NOT NULL UNIQUE,
status job_status NOT NULL,
result JSONB, -- or TEXT if you prefer
error TEXT,
current_attempt INTEGER NOT NULL DEFAULT 1,
max_attempts INTEGER NOT NULL DEFAULT 3,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
We'll also have an index on natural_key (already unique) and maybe on status for the worker to pick pending jobs.
- The `job_attempts` table:
CREATE TABLE job_attempts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
job_id UUID NOT NULL REFERENCES jobs(id),
attempt_number INTEGER NOT NULL,
status job_status NOT NULL,
result JSONB,
error TEXT,
started_at TIMESTAMP,
finished_at TIMESTAMP,
.created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
We'll have a composite unique index on (job_id, attempt_number) to ensure we don't have duplicate attempts for the same job.
And an index on status for the worker? But the worker will look for jobs with status 'pending', so we might not need an index on job_attempts.status because we update the job's status and then the worker looks at the job table.
However, if we want to query attempts by status independently, we might want an index.
Worker:
The worker will:
SELECT * FROM jobs WHERE status = 'pending' FOR UPDATE SKIP LOCKED LIMIT 1;
Then, for the selected job, create an attempt (if not already created? But we already created the attempt in the submission step? Wait, in the submission step we create the job and the first attempt with status 'pending'. Then the worker picks up the job and updates the attempt to 'running' and the job to 'running'.
Alternatively, we can have the worker create the attempt? But then we have to create the attempt in the same transaction as updating the job to 'running'. But the submission step already created the first attempt.
Let's adjust:
In submission:
- If new job: create job (status='pending') and create attempt (status='pending').
- If retry: create new attempt (status='pending') and update job status to 'pending' (and increment current_attempt).
Then the worker:
START TRANSACTION;
SELECT * FROM jobs WHERE status = 'pending' FOR UPDATE SKIP LOCKED LIMIT 1;
-- Now we have the job row locked.
-- We need to update the latest attempt (the one with status='pending' for this job) to 'running' and set started_at.
-- But how do we get the latest attempt? We can have a column in jobs that points to the current attempt? Or we can query job_attempts for the job and the maximum attempt_number that is pending.
Alternatively, we can change the design:
In the job table, we don't store the status? We always get the status from the latest attempt. But then we need to join to get the status, which is expensive.
Let's keep the job status as a cache. Then the worker:
UPDATE job_attempts
SET status = 'running', started_at = NOW()
WHERE job_id = ? AND status = 'pending' AND attempt_number = (SELECT MAX(attempt_number) FROM job_attempts WHERE job_id = ?)
RETURNING *;
Then update the job status to 'running'.
But note: there might be multiple pending attempts? We only want the latest one. We ensure that by only creating one pending attempt at a time (because when we create a new attempt, we set the job status to pending, and then the worker will pick it up and set it to running). So there should be at most one pending attempt per job.
So we can do:
UPDATE job_attempts
SET status = 'running', started_at = NOW()
WHERE id = (SELECT id FROM job_attempts WHERE job_id = ? AND status = 'pending' ORDER BY attempt_number DESC LIMIT 1)
RETURNING *;
Then update the job:
UPDATE jobs SET status = 'running', updated_at = NOW() WHERE id = ?;
Then commit.
But what if the worker crashes after updating the attempt but before updating the job? Then the job status would be 'pending' but the attempt is 'running'. We can fix this by having a background job that reconciles: if an attempt is running but the job is pending, update the job to running.
Alternatively, we can update the job first and then the attempt? But then if we update the job to running and then crash before updating the attempt, we have a running job with no running attempt? That's worse.
Let's update the attempt first, then the job. And if the job update fails, we have an attempt running but job pending. We can have a reconciliation process that sets the job status to the latest attempt's status periodically.
Or we can do both in one transaction:
BEGIN;
UPDATE job_attempts ...;
UPDATE jobs ...;
COMMIT;
Then if the transaction commits, both are updated. If it fails, neither is updated.
So the worker does:
BEGIN;
-- Lock the job row (we already did when selecting, but we can do the update by id)
UPDATE job_attempts
SET status = 'running', started_at = NOW()
WHERE job_id = ? AND status = 'pending' AND attempt_number = (SELECT MAX(attempt_number) FROM job_attempts WHERE job_id = ?)
RETURNING *;
-- Check that we updated one row. If not, then maybe another worker took it? Then we skip.
UPDATE jobs SET status = 'running', updated_at = NOW() WHERE id = ?;
COMMIT;
Then the worker runs the job.
When the job finishes:
BEGIN;
UPDATE job_attempts
SET status = ?, result = ?, error = ?, finished_at = NOW()
WHERE id = ?;
UPDATE jobs
SET status = ?, result = ?, error = ?, updated_at = NOW()
WHERE id = ?;
COMMIT;
But note: if the job fails and we want to retry, we don't automatically retry. We wait for the next submission with allow_retry.
Alternatively, we can have an automatic retry mechanism that, when a job fails, if current_attempt < max_attempts, it automatically creates a new attempt? But then we are doing a retry without the caller's explicit request? That might be acceptable for some systems.
Let's leave it as: retries are explicit via the allow_retry flag.
Summary:
- We have two tables: `jobs` and `job_attempts`.
- The `jobs` table has one row per natural_key and caches the current status.
- The `job_attempts` table records every attempt.
- We use database transactions and row-level locking to ensure that only one worker can pick a pending job and that we don't create multiple pending attempts for the same job.
Potential issues:
- What if the worker picks a job and then crashes? The attempt will be left in 'running' and the job in 'running'. We need a way to reset stuck jobs.
We can have a timeout: if an attempt has been running for more than X minutes, we consider it failed and allow a retry? Or we can have a separate process that looks for attempts with started_at older than a threshold and status 'running', and then marks them as failed (and updates the job accordingly). Then a new attempt can be created on retry.
- What if the job takes a long time? We might want to update the job's updated_at periodically to show it's still alive? But that's not necessary for the ledger.
Let's design the retry logic:
When a job fails (attempt status = 'failed'), the job status becomes 'failed'. Then, if a request comes with the same natural_key and allow_retry=true and current_attempt < max_attempts, we:
- Increment current_attempt.
- Create a new attempt with status 'pending' and attempt_number = current_attempt.
- Set job status to 'pending'.
Then the worker will pick it up.
But what if the job failed and we want to retry immediately? We can do the above in the same transaction as the submission.
Alternatively, we can have a separate endpoint to retry a job by job_id? That might be better because the natural_key might be the same but we want to retry the same job (same job_id) even if the natural_key hasn't changed? But wait, the natural_key is the business key. If the job failed and we want to retry, we are retrying the same job (same natural_key). So we don't need a separate job_id for retry? We just use the existing job.
So the submission endpoint:
POST /jobs
Body: {
"natural_key": "some-key",
"payload": {...},
"allow_retry": true, // optional, default false
"max_attempts": 3 // optional, only used when creating a new job
}
Steps:
BEGIN;
SELECT * FROM jobs WHERE natural_key = ? FOR UPDATE;
If found:
If job.status in ('completed', 'failed') and allow_retry and job.current_attempt < job.max_attempts:
job.current_attempt = job.current_attempt + 1;
INSERT INTO job_attempts (job_id, attempt_number, status) VALUES (job.id, job.current_attempt, 'pending');
job.status = 'pending';
-- update job.result and job.error? We leave them as the previous attempt? Or clear?
-- We might want to keep the previous result/error for audit, but the job's current result/error should be from the latest attempt?
-- Actually, when the new attempt starts, it will update the job's result/error. So we can leave them as they are until the new attempt finishes.
Else:
-- return the existing job (with its current status and result/error)
-- we don't create a new attempt.
COMMIT and return job.
If not found:
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts) VALUES (?, 'pending', 1, ?);
Then get the job id (using RETURNING) and insert into job_attempts (job_id, attempt_number, status) values (job_id, 1, 'pending');
COMMIT and return the new job.
Then, if we created a new job or a new attempt, we return the job (with the new attempt number?).
But note: the job's result and error are from the latest attempt. So if we are creating a new attempt, we don't clear the job's result and error? We should set them to null? Because the new attempt hasn't produced a result yet.
Let's change: when we create a new attempt (retry), we set the job's result and error to null? Or we leave the old ones?
We want the job to reflect the current state. If the new attempt is pending, then there is no result yet. So we should set job.result and job.error to null when we create a new attempt?
But then we lose the previous attempt's result? We don't, because it's in the job_attempts table.
So in the retry case:
job.result = NULL;
job.error = NULL;
Similarly, when we create a new job, we set result and error to null.
But wait: what if the job is completed and we don't allow retry? Then we return the job with the result. That's fine.
So the update for retry:
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = ? AND current_attempt < max_attempts
RETURNING *;
Then insert the new attempt.
But note: we are already in a transaction and we have the job row locked. We can do:
IF job.status in ('completed', 'failed') and allow_retry and job.current_attempt < job.max_attempts THEN
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = job.id;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job.id, job.current_attempt + 1, 'pending'); -- but we already incremented current_attempt? We did in the update.
Actually, we set current_attempt = current_attempt + 1 in the update, so we can use that new value for the attempt_number.
We can do:
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = job.id
RETURNING current_attempt as new_attempt;
Then use that new_attempt for the insert.
END IF;
This seems workable.
Let's write the full submission transaction:
WITH locked_job AS (
SELECT * FROM jobs WHERE natural_key = $1 FOR UPDATE
),
inserted_job AS (
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
SELECT $1, 'pending', 1, COALESCE($3, 3), NULL, NULL, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM locked_job)
RETURNING *
)
SELECT * FROM locked_job
UNION ALL
SELECT * FROM inserted_job
INTO job_row;
Then, if job_row is from locked_job (i.e., we found an existing job):
IF job_row.status IN ('completed', 'failed') AND $2 (allow_retry) AND job_row.current_attempt < job_row.max_attempts THEN
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = job_row.id
RETURNING current_attempt as new_attempt
INTO new_attempt;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, new_attempt, 'pending');
-- Then we need to get the updated job row? We can re-select or use the updated row from the UPDATE ... RETURNING.
-- Alternatively, we can do:
UPDATE jobs
SET ...
WHERE id = job_row.id
RETURNING * INTO updated_job;
Then use updated_job.
END IF;
But note: we are in a transaction and we have the job_row from the locked_job. We can update that row and then re-select? Or we can use the CTE to update and return the updated row.
Alternatively, we can do:
IF job_row.status IN ('completed', 'failed') AND $2 (allow_retry) AND job_row.current_attempt < job_row.max_attempts THEN
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = job_row.id
RETURNING * INTO job_row; -- now job_row is the updated one.
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, job_row.current_attempt, 'pending');
END IF;
Then, at the end, we return job_row (which is either the existing job (if no retry) or the updated job) and also we might want to return the latest attempt? We can return the job and then the client can query the attempts.
But the client might want to know the attempt number. So we can return the job with the current_attempt (which is the latest attempt number, even if it's pending).
However, note: if we didn't create a new attempt (because no retry) then the current_attempt is the same as before.
So we return the job row (which has the current_attempt and status).
But wait: if we created a new job (inserted_job) then we already inserted the first attempt? Yes, in the inserted_job CTE we only inserted the job. We need to insert the first attempt for the new job.
Let's adjust:
We have two cases:
Case 1: New job (inserted_job is not null)
-> We need to insert the first attempt.
Case 2: Existing job with retry (we updated the job and then inserted a new attempt)
-> We already inserted the new attempt.
Case 3: Existing job without retry (we didn't update or insert attempt)
-> We don't insert a new attempt.
So:
IF inserted_job is not null THEN
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (inserted_job.id, 1, 'pending');
END IF;
But note: in the existing job with retry, we already inserted the new attempt. So we don't want to insert again.
We can structure:
WITH locked_job AS (...),
inserted_job AS (...)
SELECT * FROM locked_job
UNION ALL
SELECT * FROM inserted_job
INTO job_row;
IF job_row IS NULL THEN
-- This shouldn't happen because we either lock or insert.
END IF;
IF job_row = inserted_job THEN
-- It's a new job, insert first attempt.
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, 1, 'pending');
ELSIF job_row.status IN ('completed', 'failed') AND allow_retry AND job_row.current_attempt < job_row.max_attempts THEN
-- We already updated the job and inserted the new attempt in the above IF block? Actually, we haven't done that yet.
Let's restructure:
We can do:
IF job_row.status IN ('completed', 'failed') AND allow_retry AND job_row.current_attempt < job_row.max_attempts THEN
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE id = job_row.id
RETURNING * INTO job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, job_row.current_attempt, 'pending');
END IF;
But note: we already have job_row from the CTE (which is the old value). We update and then set job_row to the updated row.
Then, if we did the update, we inserted the new attempt.
But what about the new job? We already inserted the job and then we need to insert the first attempt. We can do:
IF inserted_job IS NOT NULL THEN
-- We already inserted the job, but we haven't inserted the first attempt.
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (inserted_job.id, 1, 'pending');
-- And then set job_row to inserted_job? But we already set job_row to the result of the CTE, which is the inserted_job.
Alternatively, we can include the first attempt insertion in the inserted_job CTE? But then we are doing an insert in a CTE? We can do:
inserted_job AS (
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
SELECT $1, 'pending', 1, COALESCE($3, 3), NULL, NULL, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM locked_job)
RETURNING *
),
inserted_attempt AS (
INSERT INTO job_attempts (job_id, attempt_number, status)
SELECT id, 1, 'pending' FROM inserted_job
RETURNING *
)
But then we are inserting the attempt only if we inserted the job.
Then we select from locked_job and inserted_job.
Then, if we have an existing job and we are doing a retry, we do the update and insert attempt in the main block.
This is getting complex.
Let's simplify by using a stored procedure or by breaking into multiple steps in the application code.
Alternatively, we can do:
Step 1: Lock the job row by natural_key (or get none).
Step 2: If locked_job exists, then check if we can retry.
If yes, then update the job and insert a new attempt.
If no, then just return the locked_job.
Step 3: If locked_job doesn't exist, then insert the job and the first attempt.
But we must do this in a transaction to avoid race conditions.
We can do:
BEGIN;
-- Try to lock the existing job
SELECT * FROM jobs WHERE natural_key = $1 FOR UPDATE;
If found:
If (status in ('completed','failed') and allow_retry and current_attempt < max_attempts) then
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE natural_key = $1
RETURNING * into job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, job_row.current_attempt, 'pending');
Else
job_row = the locked job row.
End if;
Else
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
RETURNING * into job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, 1, 'pending');
End if;
COMMIT;
Return job_row.
This is clearer.
But note: the SELECT ... FOR UPDATE will lock the row if it exists. If it doesn't exist, it returns nothing. Then we insert.
However, there is a race condition: two transactions might both do the SELECT and both not find the row, and then both try to insert. But the unique constraint on natural_key will cause one to fail. We can catch that and retry? Or we can use INSERT ... ON CONFLICT ...?
We want to avoid the race condition. We can do:
INSERT INTO jobs (natural_key, ...)
VALUES ($1, ...)
ON CONFLICT (natural_key) DO UPDATE
SET ...
WHERE ...
RETURNING *;
But that's an UPSERT. We want to conditionally update only if we are allowed to retry? And we want to lock the row? The ON CONFLICT DO UPDATE will lock the row?
Actually, in PostgreSQL, INSERT ... ON CONFLICT ... DO UPDATE will acquire a row-level lock on the conflicting row. But we want to do different things depending on the existing row's state.
We can do:
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key) DO UPDATE
SET
status = CASE
WHEN EXCLUDED.status = 'pending' THEN 'pending' -- but we are not using EXCLUDED for status? We want to conditionally update.
WHEN jobs.status IN ('completed','failed') AND $2 (allow_retry) AND jobs.current_attempt < jobs.max_attempts
THEN 'pending'
ELSE jobs.status
END,
current_attempt = CASE
WHEN jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
THEN jobs.current_attempt + 1
ELSE jobs.current_attempt
END,
result = CASE
WHEN jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
THEN NULL
ELSE jobs.result
END,
error = CASE
WHEN jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
THEN NULL
ELSE jobs.error
END,
updated_at = NOW()
WHERE jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
RETURNING *;
But note: the WHERE clause in the DO UPDATE will only update if the condition is true. Otherwise, the row is not updated? Actually, the UPDATE part is only executed if the WHERE condition is true. Otherwise, the row is not updated and the INSERT fails? No, the ON CONFLICT DO UPDATE is executed when there's a conflict. But if the WHERE condition is false, then the row is not updated and the INSERT is not done? Actually, the ON CONFLICT clause has two parts: the DO UPDATE and the DO NOTHING. We are using DO UPDATE, but if the WHERE condition is false, then the UPDATE is not executed and we get the existing row? Actually, in PostgreSQL, if the WHERE condition in DO UPDATE is false, then the UPDATE is not executed and the row is not updated, but the INSERT is not done either? We are in a conflict, so we are trying to insert a row that already exists. If the WHERE condition is false, then we do nothing? Actually, the ON CONFLICT DO UPDATE will update the row if the WHERE condition is true. If the WHERE condition is false, then the row is not updated and the INSERT is not done, so we get the existing row? But then we are not returning anything? We need to return the existing row.
We can use:
INSERT ... ON CONFLICT (natural_key) DO UPDATE SET ... WHERE ... RETURNING *;
If the WHERE condition is false, then the UPDATE is not executed and the INSERT is not done, so we don't get a row? Actually, the RETURNING will return the row that was inserted or updated. If the UPDATE was not executed (because WHERE false) then we don't get a row? That's not what we want.
We want to return the existing row even if we didn't update. So we can do:
INSERT ... ON CONFLICT (natural_key) DO UPDATE SET ... WHERE ... RETURNING *
UNION ALL
SELECT * FROM jobs WHERE natural_key = $1;
But that would return two rows if we updated? We only want one.
Alternatively, we can use a CTE:
WITH upsert AS (
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key)
DO UPDATE SET
status = 'pending',
current_attempt = jobs.current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
RETURNING *
)
SELECT * FROM upsert
UNION ALL
SELECT * FROM jobs WHERE natural_key = $1 AND NOT EXISTS (SELECT 1 FROM upsert);
This will return the row from the upsert if we inserted or updated, otherwise it returns the existing row.
But note: if we update, then the upsert returns the updated row. If we don't update (because condition false) then the upsert returns nothing and we get the existing row from the second SELECT.
However, what if the existing row is in a state that we don't update (e.g., running)? Then we return the existing row without change.
But wait: we are not inserting the job_attempts in this upsert. We only update the job. We need to insert the job_attempts for the new attempt (if we updated the job) and for the new job (if we inserted).
We can do:
WITH upsert_job AS (
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key)
DO UPDATE SET
status = 'pending',
current_attempt = jobs.current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE jobs.status IN ('completed','failed') AND $2 AND jobs.current_attempt < jobs.max_attempts
RETURNING *
),
job_row AS (
SELECT * FROM upsert_job
UNION ALL
SELECT * FROM jobs WHERE natural_key = $1 AND NOT EXISTS (SELECT 1 FROM upsert_job)
)
INSERT INTO job_attempts (job_id, attempt_number, status)
SELECT
job_row.id,
CASE
WHEN job_row.current_attempt = 1 AND job_row.created_at = (SELECT created_at FROM job_attempts WHERE job_id = job_row.id ORDER BY attempt_number DESC LIMIT 1)
THEN 1 -- but wait, we don't have the job_attempts row yet?
ELSE job_row.current_attempt
END,
'pending'
FROM job_row
WHERE
-- We only want to insert an attempt if:
-- 1. The job is new (so no attempts exist) -> then we insert attempt 1.
-- 2. The job was updated (meaning we incremented current_attempt) -> then we insert the new attempt_number.
-- But how do we know if the job was updated? We can check if the job_row came from upsert_job and if the current_attempt is greater than the maximum attempt_number in job_attempts?
-- Alternatively, we can do:
-- For the upsert_job, if it's an insert, then we insert attempt 1.
-- If it's an update, then we insert the new current_attempt.
-- But we don't have that information.
This is getting very complex.
Given the complexity, I think it's better to do it in two steps with a lock:
Step 1: Lock the job row (or get none).
Step 2: If locked, then conditionally update and insert attempt.
Step 3: If not locked, then insert job and attempt.
But we must handle the race condition of two transactions trying to insert the same natural_key.
We can do:
BEGIN;
-- Try to lock the existing job. If it exists, we get it.
SELECT * FROM jobs WHERE natural_key = $1 FOR UPDATE;
If found:
If (status in ('completed','failed') and allow_retry and current_attempt < max_attempts) then
-- Update the job and insert a new attempt.
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE natural_key = $1
RETURNING * into job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, job_row.current_attempt, 'pending');
Else
job_row = the locked job row.
End if;
Else
-- Insert the job and the first attempt.
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
RETURNING * into job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, 1, 'pending');
End if;
COMMIT;
Return job_row.
But what about the race condition when two transactions do the SELECT at the same time and both don't find the row? Then both will try to insert. The first one will succeed, the second one will fail on the unique constraint. We can catch that and retry? Or we can use a lock on the table?
We can use advisory locks? Or we can use a separate table for generating natural keys?
Alternatively, we can use INSERT ... ON CONFLICT ... to handle the insert and then do the conditional update in the ON CONFLICT clause? But then we have to also insert the job_attempts.
Given the complexity, I think we should use a stored procedure that does:
LOCK TABLE jobs IN SHARE MODE? That would be too heavy.
Another idea: use a separate table for job submissions that acts as a lock?
Let's think: we want to ensure that only one job per natural_key is in the jobs table. We have a unique constraint. So if two transactions try to insert the same natural_key, one will succeed and the other will fail with a unique violation.
We can catch that error and then retry the transaction? But that's messy.
Alternatively, we can do:
BEGIN;
-- Try to insert the job. If it fails due to unique constraint, then we select the existing job and do the retry logic.
So:
Step 1: Try to insert the job (with status='pending', current_attempt=1) for the natural_key. If it succeeds, then we insert the first attempt and return.
Step 2: If the insert fails (unique violation), then we select the existing job for update and do the retry logic.
We can do:
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key) DO NOTHING
RETURNING *;
If we get a row, then we insert the first attempt and return.
If we don't get a row, then we select the existing job for update and do the retry logic.
But note: the ON CONFLICT DO NOTHING will not lock the row. So we might have a race condition: two transactions both try to insert, one succeeds and inserts the job and attempt. The other does nothing and then selects the job. But the job might be in a state that we want to retry? But the first transaction already created the job with status='pending'. So the second transaction will see a job with status='pending' and won't retry (because we only retry on completed or failed). So that's safe.
However, what if the job is in a terminal state and we want to retry? Then the second transaction will select the job and then update it and insert a new attempt. But note: the first transaction inserted the job and set status='pending'. So if the job is pending, we don't retry. So that's safe.
But what if the job is completed and we want to retry? Then the second transaction will see the completed job and update it to pending and insert a new attempt. But note: the first transaction inserted the job and set it to pending. So if the job was already completed, then the first transaction wouldn't have inserted because the job exists? Wait, the first transaction tried to insert and got a conflict, so it did nothing. Then the second transaction selects the job (which is completed) and then updates it to pending and inserts a new attempt. That's correct.
So the algorithm:
BEGIN;
-- Try to create a new job (if it doesn't exist)
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES ($1, 'pending', 1, COALESCE($3,3), NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key) DO NOTHING
RETURNING *;
If we get a row (new job):
INSERT INTO job_attempts (job_id, attempt_number, status) VALUES (new_job.id, 1, 'pending');
RETURN new_job;
Else (job already exists):
SELECT * FROM jobs WHERE natural_key = $1 FOR UPDATE; -- lock the existing job
If job.status in ('completed','failed') and $2 (allow_retry) and job.current_attempt < job.max_attempts:
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE natural_key = $1
RETURNING * into job_row;
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (job_row.id, job_row.current_attempt, 'pending');
RETURN job_row;
Else:
RETURN the locked job row (without change).
COMMIT;
This should be safe and handle the race condition.
Let's code it in a stored procedure or in the application.
However, note: the first INSERT might succeed and then we insert the attempt. But what if the application crashes after inserting the job but before inserting the attempt? Then we have a job with no attempt? That's inconsistent.
We must do both in the same transaction. So:
BEGIN;
INSERT INTO jobs ... ON CONFLICT DO NOTHING RETURNING *;
If we get a row:
INSERT INTO job_attempts ...;
COMMIT;
Return the job.
Else:
SELECT ... FOR UPDATE;
... update and insert attempt if retry ...
COMMIT;
Return the job.
But if the first INSERT returns a row, we are in the same transaction and we insert the attempt. Then commit. So that's atomic.
What if the first INSERT returns a row, then we insert the attempt, but then the transaction fails? Then both are rolled back.
So this should be safe.
Let's write the pseudocode for the application:
function submit_job(natural_key, payload, allow_retry=false, max_attempts=3):
db.begin()
try:
# Try to create a new job
job = db.execute("""
INSERT INTO jobs (natural_key, status, current_attempt, max_attempts, result, error, created_at, updated_at)
VALUES (%s, 'pending', 1, %s, NULL, NULL, NOW(), NOW())
ON CONFLICT (natural_key) DO NOTHING
RETURNING *;
""", [natural_key, max_attempts]).fetchone()
if job:
# New job created, insert first attempt
db.execute("""
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (%s, 1, 'pending');
""", [job.id])
db.commit()
return job
else:
# Job already exists, lock it
job = db.execute("""
SELECT * FROM jobs WHERE natural_key = %s FOR UPDATE;
""", [natural_key]).fetchone()
if job.status in ['completed', 'failed'] and allow_retry and job.current_attempt < job.max_attempts:
# Retry: update job and insert new attempt
job = db.execute("""
UPDATE jobs
SET status = 'pending',
current_attempt = current_attempt + 1,
result = NULL,
error = NULL,
updated_at = NOW()
WHERE natural_key = %s
RETURNING *;
""", [natural_key]).fetchone()
db.execute("""
INSERT INTO job_attempts (job_id, attempt_number, status)
VALUES (%s, %s, 'pending');
""", [job.id, job.current_attempt])
db.commit()
return job
else:
# No retry, just return the existing job
db.commit()
return job
except Exception as e:
db.rollback()
raise e
This seems solid.
But note: what if the job exists and is in a state that we don't update (e.g., running)? Then we just return the job.
Also, what if the job exists and is pending? Then we return the job without change. That means we don't create a new attempt. That's correct because the job is already in progress.
What if the job exists and is completed, but allow_retry is false? Then we return the completed job.
What if the job exists and is failed, but allow_retry is false? Then we return the failed job.
What if the job exists and is failed, allow_retry is true, but current_attempt >= max_attempts? Then we return the failed job without change.
This meets the requirements.
Now, the worker:
The worker will:
while True:
db.begin()
try:
# Pick a pending job
job = db.execute("""
SELECT * FROM jobs
WHERE status = 'pending'
ORDER BY created_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED;
""").fetchone()
if not job:
db.commit()
sleep(1)
continue
# Get the latest attempt for this job that is pending (there should be only one)
attempt = db.execute("""
SELECT * FROM job_attempts
WHERE job_id = %s AND status = 'pending'
ORDER BY attempt_number DESC
LIMIT 1
FOR UPDATE;
""", [job.id]).fetchone()
if not attempt:
# This should not happen: job is pending but no pending attempt?
# Maybe we have a consistency issue. We can set the job status to something else? Or create an attempt?
# Let's create an attempt? But we might be in a retry? Actually, the job should have a pending attempt if it's pending.
# We can log an error and set the job status to 'failed'? Or we can skip and try the next job.
db.rollback()
continue
# Start the attempt
db.execute("""
UPDATE job_attempts
SET status = 'running', started_at = NOW()
WHERE id = %s;
""", [attempt.id])
db.execute("""
UPDATE jobs
SET status = 'running', updated_at = NOW()
WHERE id = %s;
""", [job.id])
db.commit()
# Now run the job (outside of the transaction)
try:
result = run_job(job.id, attempt.id, payload) # we need to get the payload from somewhere? Maybe from the job? We don't store the payload in the job table?
# If the job requires the payload, we must store it somewhere. We can store it in the job_attempts? But then we are storing the same payload for each attempt?
# Actually, the payload is the same for all attempts? Or does it change?
# We are using natural_key to identify the job, but the payload might be different for each attempt?
# Let's assume the payload is the same for all attempts of the same job? Then we can store it in the job table?
# But wait: the job table is for the current job. If we retry, we might want to change the payload? Then we need to store the payload per attempt.
# So we should store the payload in the job_attempts table.
# But then, when we submit a job, we must store the payload in the attempt.
# So in the submission code, when we create a new attempt (first or retry), we must store the payload.
# We didn't include payload in the above. Let's adjust:
# In the jobs table, we don't store the payload. In the job_attempts table, we have a column `payload` (JSONB).
# Then, when we create an attempt, we set the payload.
# So in the submission code:
# For new job:
# INSERT INTO job_attempts (job_id, attempt_number, status, payload) VALUES (job.id, 1, 'pending', $2);
# For retry:
# INSERT INTO job_attempts (job_id, attempt_number, status, payload) VALUES (job_row.id, job_row.current_attempt, 'pending', $2);
# And then the worker can get the payload from the attempt.
# So we need to adjust the submission code to accept a payload and store it in the attempt.
except Exception as e:
# Job failed
db.begin()
db.execute("""
UPDATE job_attempts
SET status = 'failed', error = %s, finished_at = NOW()
WHERE id = %s;
""", [str(e), attempt.id])
db.execute("""
UPDATE jobs
SET status = 'failed', error = %s, updated_at = NOW()
WHERE id = %s;
""", [str(e), job.id])
db.commit()
else:
# Job succeeded
db.begin()
db.execute("""
UPDATE job_attempts
SET status = 'completed', result = %s, finished_at = NOW()
WHERE id = %s;
""", [json.dumps(result), attempt.id])
db.execute("""
UPDATE jobs
SET status = 'completed', result = %s, updated_at = NOW()
WHERE id = %s;
""", [json.dumps(result), job.id])
db.commit()
except Exception as e:
db.rollback()
log_error(e)
This worker design uses FOR UPDATE SKIP LOCKED to avoid multiple workers picking the same job.
But note: we are locking the job and then the attempt. We must lock the job first, then the attempt? Or we can lock the attempt first?
We lock the job to prevent other workers from picking the same job. Then we lock the attempt to prevent other workers from picking the same attempt? But there should be only one pending attempt per job.
We are using two separate SELECT ... FOR UPDATE. We lock the job first, then the attempt. This is okay.
However, what if two workers pick the same job? They both try to lock the job. The first one gets the lock, the second one waits. Then the first one updates the job to running and the attempt to running. Then the second one, when it gets the lock, will see the job status is no longer pending? Because we updated it to running. So the second worker's SELECT for pending jobs won't return that job. So it's safe.
But note: we are doing:
SELECT * FROM jobs WHERE status = 'pending' ... FOR UPDATE SKIP LOCKED.
This will lock the job row. Then we select the attempt. But what if another worker has already locked the attempt? We are locking the job first, then the attempt. But the other worker might have locked the attempt first?
Actually, we are locking the job row, and then we select the attempt for that job. Since we have the job locked, no other worker can update the job status until we commit. So they won't see the job as pending. So they won't try to pick it.
But what if two workers both select the same job as pending? That's possible if they both run the SELECT at the same time and the job is pending. Then both will lock the job? No, the first one will lock the job, the second one will wait (because SKIP LOCKED will skip the locked row? Actually, SKIP LOCKED will skip rows that are locked by other transactions. So the second worker will not get that job because it's locked. So only one worker will get the job.
So the worker design is safe.
We must also consider:
- Stuck jobs: if a worker crashes after setting the attempt to running but before finishing, then the attempt and job are left in 'running'. We need a way to reset them.
We can have a cron job that:
Finds attempts with status='running' and started_at older than X minutes, and sets them to 'failed'. Then sets the job status to 'failed'.
Then, if allow_retry is allowed, a new submission can retry.
Alternatively, we can have a timeout in the worker: if a job takes too long, we kill it? But that's more complex.
Let's leave it as a separate process.
Summary:
Tables:
jobs:
id (PK)
natural_key (unique)
status
result
error
current_attempt
max_attempts
created_at
updated_at
job_attempts:
id (PK)
job_id (FK to jobs.id)
attempt_number
status
payload (JSONB) -- we added this
result
error
started_at
finished_at
created_at -- maybe we don't need this, we have started_at and finished_at?
We have an index on job_attempts(job_id, attempt_number) and maybe on (job_id, status) for the worker to find pending attempts? But the worker uses the job table to find pending jobs.
The worker uses:
SELECT * FROM jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED;
Then for that job, it finds the pending attempt.
We assume that for a pending job, there is exactly one pending attempt (the latest one). We enforce that by only creating one pending attempt at a time.
This design should meet the requirements.
Let me know if you have any questions.
I'll design a comprehensive async job idempotency ledger system that balances natural keys with idempotency keys while ensuring exactly-once processing semantics and full auditability.
Core Design Principles
- Natural Keys: Business-level unique identifiers (e.g.,
order_id, user_id + action_type)
- Idempotency Keys: System-generated UUIDs for deduplication (client-provided or server-generated)
- Exactly-Once: Prevent duplicate processing while allowing safe retries
- Audit Trail: Complete history of all attempts with immutable records
Schema Design
1. Jobs Table (Source of Truth)
CREATE TABLE jobs (
-- Surrogate primary key
job_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Natural business key (deterministic hash for indexing)
natural_key_hash BYTEA NOT NULL, -- SHA-256 of natural_key
natural_key_type VARCHAR(50) NOT NULL, -- e.g., 'order_processed', 'user_notification'
natural_key JSONB NOT NULL, -- Original business key components
-- Idempotency control
idempotency_key UUID UNIQUE, -- Client-provided or server-generated
idempotency_window INTERVAL NOT NULL DEFAULT '24 hours',
-- Status lifecycle
status VARCHAR(20) NOT NULL
CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled')),
-- Execution metadata
priority SMALLINT DEFAULT 0,
scheduled_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
max_attempts INTEGER NOT NULL DEFAULT 3,
-- Current state (denormalized from latest attempt)
result JSONB,
error_message TEXT,
completed_at TIMESTAMPTZ,
-- Timestamps
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Constraints
CONSTRAINT valid_scheduling CHECK (
(scheduled_at IS NULL) OR
(scheduled_at <= expires_at) OR
(expires_at IS NULL)
)
);
-- Composite index for natural key lookups
CREATE UNIQUE INDEX idx_jobs_natural_key
ON jobs (natural_key_hash, natural_key_type)
WHERE status NOT IN ('cancelled', 'failed');
-- For idempotency key lookups (already unique)
CREATE INDEX idx_jobs_idempotency_key ON jobs(idempotency_key)
WHERE idempotency_key IS NOT NULL;
-- For time-based queries
CREATE INDEX idx_jobs_scheduled ON jobs(scheduled_at, status)
WHERE scheduled_at IS NOT NULL;
2. Job Attempts Table (Immutable Audit Log)
CREATE TABLE job_attempts (
attempt_id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL REFERENCES jobs(job_id) ON DELETE CASCADE,
-- Attempt metadata
attempt_number INTEGER NOT NULL,
worker_id VARCHAR(100), -- Which worker processed this
queue_name VARCHAR(100), -- Which queue it came from
-- Status and timing
status VARCHAR(20) NOT NULL
CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled')),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
duration_ms INTEGER, -- Computed: EXTRACT(EPOCH FROM (finished_at - started_at)) * 1000
-- Execution details
input_payload JSONB NOT NULL, -- What was executed (immutable snapshot)
result_payload JSONB, -- What was returned
error_details JSONB, -- Structured error: {type, message, stack_trace, retryable}
-- System metadata
infrastructure_metadata JSONB, -- {host, pod, region, version}
-- Timestamps (always set at record creation)
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Constraints
CONSTRAINT valid_attempt_timing CHECK (
(started_at IS NULL) OR
(finished_at IS NULL) OR
(finished_at >= started_at)
),
CONSTRAINT positive_duration CHECK (
duration_ms IS NULL OR duration_ms >= 0
),
CONSTRAINT unique_attempt_per_job UNIQUE (job_id, attempt_number)
);
-- Composite index for job history
CREATE INDEX idx_job_attempts_job_id ON job_attempts(job_id, attempt_number DESC);
-- For searching by result/error patterns
CREATE INDEX idx_job_attempts_result_gin ON job_attempts USING GIN(result_payload);
CREATE INDEX idx_job_attempts_error_gin ON job_attempts USING GIN(error_details);
-- For time-range analysis
CREATE INDEX idx_job_attempts_created ON job_attempts(created_at DESC);
3. Idempotency Keys Table (For Client-Provided Keys)
CREATE TABLE idempotency_keys (
idempotency_key UUID PRIMARY KEY,
job_id UUID NOT NULL REFERENCES jobs(job_id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
-- Optional: TTL for automatic cleanup
CONSTRAINT valid_expiry CHECK (expires_at > created_at)
);
-- For TTL-based cleanup
CREATE INDEX idx_idempotency_expiry ON idempotency_keys(expires_at)
WHERE expires_at IS NOT NULL;
Exactly-Once Processing Flow
Job Submission (Idempotent API)
async def submit_job(
natural_key: dict, # {'order_id': '123', 'action': 'process_payment'}
payload: dict,
idempotency_key: Optional[UUID] = None,
priority: int = 0,
scheduled_at: Optional[datetime] = None,
ttl: timedelta = timedelta(hours=24)
) -> JobResponse:
"""
Submits a job with exactly-once semantics.
Three cases:
1. New natural key + no idempotency key → Create new job
2. Existing natural key → Return existing job (deduplication)
3. New idempotency key (but existing natural key) → New attempt with same natural key?
Typically: reject or create separate job type
"""
natural_key_hash = sha256(json.dumps(natural_key, sort_keys=True).encode()).digest()
natural_key_type = f"{natural_key.get('resource')}_{natural_key.get('action')}"
async with db.transaction(isolation_level=SERIALIZABLE):
# 1. Check for existing natural key (within window)
existing_job = await db.fetchrow("""
SELECT job_id, status, current_attempt, max_attempts
FROM jobs
WHERE natural_key_hash = $1
AND natural_key_type = $2
AND status NOT IN ('cancelled', 'failed')
AND (expires_at IS NULL OR expires_at > NOW())
FOR UPDATE SKIP LOCKED
""", natural_key_hash, natural_key_type)
if existing_job:
# Exact duplicate detected - return existing job
return await get_job_response(existing_job.job_id)
# 2. Check for idempotency key reuse
if idempotency_key:
existing_by_idempotency = await db.fetchrow("""
SELECT job_id FROM idempotency_keys
WHERE idempotency_key = $1
""", idempotency_key)
if existing_by_idempotency:
return await get_job_response(existing_by_idempotency.job_id)
# 3. Create new job
job_id = await db.fetchval("""
INSERT INTO jobs (
natural_key_hash, natural_key_type, natural_key,
idempotency_key, status, priority,
scheduled_at, expires_at, max_attempts
)
VALUES ($1, $2, $3, $4, 'pending', $5, $6, $7, $8)
RETURNING job_id
""",
natural_key_hash, natural_key_type,
json.dumps(natural_key),
idempotency_key, priority, scheduled_at,
NOW() + ttl if ttl else None,
3 # default max_attempts
)
# 4. Create first attempt (immutable record)
await db.execute("""
INSERT INTO job_attempts (
job_id, attempt_number, status,
input_payload, infrastructure_metadata
)
VALUES ($1, 1, 'pending', $2, $3)
""", job_id, json.dumps(payload), json.dumps(get_infrastructure_metadata()))
# 5. Store idempotency key if provided
if idempotency_key:
await db.execute("""
INSERT INTO idempotency_keys (idempotency_key, job_id, expires_at)
VALUES ($1, $2, $3)
""", idempotency_key, job_id, NOW() + ttl if ttl else None)
# 6. Enqueue to priority queue (Redis/RabbitMQ)
await enqueue_job(job_id, priority)
return await get_job_response(job_id)
Worker Processing with Exactly-Once
async def process_job(job_id: UUID):
"""Worker processes job with automatic retry logic"""
async with db.transaction(isolation_level=REPEATABLE_READ):
# 1. Atomically claim the job
job = await db.fetchrow("""
UPDATE jobs
SET status = 'processing',
updated_at = NOW()
WHERE job_id = $1
AND status = 'pending'
AND (scheduled_at IS NULL OR scheduled_at <= NOW())
RETURNING *
""", job_id)
if not job:
raise JobNotReadyError("Job not in pending state or scheduled for future")
# 2. Get the pending attempt (should be exactly one)
attempt = await db.fetchrow("""
SELECT * FROM job_attempts
WHERE job_id = $1
AND status = 'pending'
AND attempt_number = (
SELECT MAX(attempt_number)
FROM job_attempts
WHERE job_id = $1
)
FOR UPDATE SKIP LOCKED
""", job_id)
if not attempt:
raise ConsistencyError("Pending job without pending attempt")
# 3. Mark attempt as processing
await db.execute("""
UPDATE job_attempts
SET status = 'processing',
started_at = NOW(),
worker_id = $1
WHERE attempt_id = $2
""", get_worker_id(), attempt.attempt_id)
# 4. Execute outside transaction
try:
payload = json.loads(attempt.input_payload)
result = await execute_job_logic(payload, job.natural_key)
async with db.transaction():
# 5. Record success
await db.execute("""
UPDATE job_attempts
SET status = 'completed',
result_payload = $1,
finished_at = NOW(),
duration_ms = EXTRACT(EPOCH FROM (NOW() - started_at)) * 1000
WHERE attempt_id = $2
""", json.dumps(result), attempt.attempt_id)
await db.execute("""
UPDATE jobs
SET status = 'completed',
result = $1,
completed_at = NOW(),
updated_at = NOW()
WHERE job_id = $2
""", json.dumps(result), job_id)
except Exception as e:
error_details = {
"type": type(e).__name__,
"message": str(e),
"stack_trace": traceback.format_exc(),
"retryable": is_retryable_error(e)
}
async with db.transaction():
await db.execute("""
UPDATE job_attempts
SET status = 'failed',
error_details = $1,
finished_at = NOW(),
duration_ms = EXTRACT(EPOCH FROM (NOW() - started_at)) * 1000
WHERE attempt_id = $2
""", json.dumps(error_details), attempt.attempt_id)
# Check if we should retry
current_attempt = attempt.attempt_number + 1
if current_attempt <= job.max_attempts and error_details["retryable"]:
# Create retry attempt
await db.execute("""
INSERT INTO job_attempts (
job_id, attempt_number, status,
input_payload, infrastructure_metadata
)
VALUES ($1, $2, 'pending', $3, $4)
""", job_id, current_attempt,
attempt.input_payload, # Same payload
json.dumps(get_infrastructure_metadata()))
await db.execute("""
UPDATE jobs
SET status = 'pending',
updated_at = NOW()
WHERE job_id = $1
""", job_id)
await enqueue_job(job_id, job.priority, delay=calculate_backoff(attempt.attempt_number))
else:
# Permanent failure
await db.execute("""
UPDATE jobs
SET status = 'failed',
error_message = $1,
updated_at = NOW()
WHERE job_id = $2
""", error_details["message"], job_id)
Audit & Query Patterns
1. Get Job with Full History
WITH job_details AS (
SELECT
j.*,
ja_latest.result_payload as final_result,
ja_latest.error_details as final_error,
ja_latest.completed_at as final_completed_at
FROM jobs j
LEFT JOIN LATERAL (
SELECT * FROM job_attempts
WHERE job_id = j.job_id
ORDER BY attempt_number DESC
LIMIT 1
) ja_latest ON true
WHERE j.job_id = $1
)
SELECT
jd.*,
json_agg(
json_build_object(
'attempt_number', ja.attempt_number,
'status', ja.status,
'started_at', ja.started_at,
'finished_at', ja.finished_at,
'duration_ms', ja.duration_ms,
'result', ja.result_payload,
'error', ja.error_details,
'worker_id', ja.worker_id
) ORDER BY ja.attempt_number
) as attempts
FROM job_details jd
LEFT JOIN job_attempts ja ON jd.job_id = ja.job_id
GROUP BY jd.job_id;
2. Find Duplicate Submissions (Natural Key)
SELECT
natural_key_type,
natural_key,
COUNT(*) as execution_count,
MIN(created_at) as first_seen,
MAX(completed_at) as last_completed,
bool_and(status = 'completed') as all_succeeded
FROM jobs
WHERE created_at >= NOW() - INTERVAL '7 days'
GROUP BY natural_key_type, natural_key
HAVING COUNT(*) > 1
ORDER BY execution_count DESC;
3. Idempotency Key Reuse Detection
SELECT
idempotency_key,
COUNT(*) as reuse_count,
MIN(created_at) as first_used,
array_agg(DISTINCT natural_key_type) as job_types
FROM idempotency_keys ik
JOIN jobs j ON ik.job_id = j.job_id
GROUP BY idempotency_key
HAVING COUNT(*) > 1;
4. SLA & Performance Analysis
SELECT
natural_key_type,
status,
COUNT(*) as count,
AVG(duration_ms) as avg_duration_ms,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_ms) as p50_duration_ms,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY duration_ms) as p95_duration_ms,
MAX(duration_ms) as max_duration_ms
FROM job_attempts ja
JOIN jobs j ON ja.job_id = j.job_id
WHERE ja.started_at >= NOW() - INTERVAL '1 day'
GROUP BY natural_key_type, status;
Consistency Guarantees
1. Natural Key Uniqueness (Within Time Window)
- Mechanism: Unique index on
(natural_key_hash, natural_key_type) for non-terminal statuses
- Trade-off: Allows re-execution after failure (by cancelling old job first)
- Implementation: Application must cancel previous job before resubmitting new one with same natural key
2. Idempotency Key Uniqueness (Absolute)
- Mechanism: Unique constraint on
idempotency_key (with NULL exclusion)
- Guarantee: Same idempotency key always maps to same job forever
- Cleanup: TTL-based expiration (default 24h)
3. Exactly-Once Attempt Execution
- Mechanism:
SELECT ... FOR UPDATE SKIP LOCKED + atomic status transition
- Isolation:
REPEATABLE_READ prevents phantom reads during claim
- Recovery: Stuck
processing jobs → timeout → reset to pending after configurable period
Operational Concerns
1. Stuck Job Recovery
-- Reset jobs stuck in 'processing' for > 1 hour
UPDATE jobs j
SET status = 'failed',
error_message = 'Worker timeout - job stuck in processing state'
FROM (
SELECT job_id
FROM job_attempts
WHERE status = 'processing'
AND started_at < NOW() - INTERVAL '1 hour'
GROUP BY job_id
) stuck
WHERE j.job_id = stuck.job_id
AND j.status = 'processing';
2. Data Retention Policy
-- Archive old jobs (partitioning recommended for scale)
CREATE TABLE jobs_archive (LIKE jobs INCLUDING ALL);
CREATE TABLE job_attempts_archive (LIKE job_attempts INCLUDING ALL);
-- Move jobs older than 90 days
INSERT INTO jobs_archive
SELECT * FROM jobs
WHERE completed_at < NOW() - INTERVAL '90 days'
AND status IN ('completed', 'failed', 'cancelled');
-- Keep recent failures for debugging (last 30 days)
DELETE FROM job_attempts
WHERE created_at < NOW() - INTERVAL '30 days'
AND job_id IN (
SELECT job_id FROM jobs
WHERE completed_at < NOW() - INTERVAL '90 days'
);
3. Monitoring Queries
-- Queue depth
SELECT
status,
COUNT(*) as count,
AVG(EXTRACT(EPOCH FROM (NOW() - created_at))) as avg_age_seconds
FROM jobs
WHERE status IN ('pending', 'processing')
GROUP BY status;
-- Retry rate
SELECT
natural_key_type,
COUNT(*) FILTER (WHERE attempt_number > 1) as retries,
COUNT(*) as total,
ROUND(COUNT(*) FILTER (WHERE attempt_number > 1) * 100.0 / COUNT(*), 2) as retry_rate_pct
FROM job_attempts
WHERE created_at >= NOW() - INTERVAL '1 day'
GROUP BY natural_key_type
HAVING COUNT(*) > 100;
API Surface
class JobLedger:
async def submit(
self,
natural_key: dict,
payload: dict,
idempotency_key: Optional[UUID] = None,
priority: int = 0,
scheduled_at: Optional[datetime] = None,
ttl: timedelta = timedelta(hours=24)
) -> JobSubmissionResponse:
"""Submit job with deduplication"""
async def get(self, job_id: UUID) -> JobDetailResponse:
"""Get job with full attempt history"""
async def get_by_natural_key(
self,
natural_key: dict,
include_completed: bool = False
) -> List[JobSummary]:
"""Find jobs by natural key"""
async def get_by_idempotency_key(
self,
idempotency_key: UUID
) -> Optional[JobSummary]:
"""Lookup by idempotency key"""
async def cancel(self, job_id: UUID) -> bool:
"""Cancel pending/processing job"""
async def retry(
self,
job_id: UUID,
max_attempts: Optional[int] = None
) -> JobSubmissionResponse:
"""Manually retry failed job"""
async def list_attempts(
self,
job_id: UUID,
limit: int = 50,
offset: int = 0
) -> PaginatedAttemptResponse:
"""Paginated attempt history"""
Key Design Decisions
- Natural Key Hash: SHA-256 for fixed-length indexing, preserves original in JSONB
- Status in Both Tables: Denormalized for performance, always kept in sync transactionally
- Immutable Attempts: Jobs table holds current state, attempts hold history → enables full audit
- Two-Level Deduplication:
- Natural key: prevents concurrent processing of same business event
- Idempotency key: prevents duplicate submissions (client-side)
- Serializable Isolation: Prevents race conditions in submission flow
- TTL on Idempotency Keys: Prevents indefinite growth, balances deduplication needs
- Worker Claim Pattern:
FOR UPDATE SKIP LOCKED + atomic status transition ensures exactly-once
Scaling Considerations
- Partitioning: Range partition
jobs by created_at (monthly) + hash on natural_key_hash
- Index Strategy:
- Primary:
(natural_key_hash, natural_key_type) for business lookups
- Secondary:
idempotency_key for client deduplication
- Tertiary:
(status, scheduled_at) for worker queue
- Archival: Time-based partitioning + automatic archiving to S3/Blob storage
- Read Replicas: All audit queries can run on replicas; writes go to primary
This design provides strong idempotency through dual-key system, exactly-once through transactional claims, and full auditability through immutable attempt records while maintaining performance at scale.