task_id: a unique identifier for the task (this will be used for idempotency, so it must be unique across the table and the DLQ? or just the main table?
Note: Once a task fails and goes to DLQ, we might want to re-queue it? So we might want to allow the same task_id in the main queue if it was in DLQ and then re-queued?
But for idempotency, we want to avoid processing the same task (with the same task_id) multiple times at the same time.
However, if a task fails and goes to DLQ, and then we decide to retry it, we might re-insert it with the same task_id? But then we have to consider if we are going to allow the same task_id to be processed again after a certain time?
Alternatively, we can have a separate table for completed tasks (or processed task_ids) to check against. But that might be heavy.
Let's think: the idempotency key is usually for a given request (or task submission) to avoid duplicate processing. Once a task is completed (successfully) we don't want to process it again.
But if it fails and goes to DLQ, and then we decide to retry, we are essentially submitting the same task again? So we might want to allow the same task_id to be re-queued after it's in DLQ?
However, if we are using the same task_id for a retry, then when we re-queue we are going to have the same task_id in the main queue again. So we must allow the same task_id to be inserted again after it's in DLQ?
But then we have to check both the main queue and the DLQ for the same task_id?
Alternatively, we can have a separate table for "processed task_ids" that we never remove, but that would grow forever.
Another approach: when we insert a task, we check the main queue and the DLQ for the same task_id and if it exists and is not in a terminal state (like completed or in DLQ for a long time) then we reject?
But let's simplify: we are going to use the main queue for tasks that are pending or being processed, and the DLQ for tasks that have failed.
We want to avoid having the same task_id in the main queue at the same time (to avoid duplicate processing). But if a task is in the DLQ, we might want to re-queue it, so we can remove it from the DLQ and put it back in the main queue?
Then when we re-queue, we are creating a new record in the main queue with the same task_id? So we must allow the same task_id to be in the main queue again after it's been in the DLQ?
How about: we have a status field in the main queue and the DLQ? But then we are mixing two tables.
Alternatively, we can have one table for all tasks and a status field that indicates: pending, processing, completed, failed (and then maybe we have a separate DLQ table that just points to the failed tasks?).
Let me propose:
One table: tasks
id (primary key)
task_id (unique, the idempotency key)
payload (JSON or text)
status: enum('pending', 'processing', 'completed', 'failed')
attempts: integer (number of attempts so far)
max_attempts: integer (configurable per task or global)
last_error: text (optional, for the last failure)
scheduled_at: timestamp (when it is scheduled to run, for delayed tasks)
created_at: timestamp
updated_at: timestamp
And then we don't have a separate DLQ table. Instead, we have a status 'failed' and we can query for failed tasks to move to a DLQ (or just leave them in the same table).
But then the DLQ is just a view of the failed tasks?
However, the requirement says "persistent work queue" and "DLQ", so we might want to have a separate table for the DLQ to isolate the failed tasks and maybe have different retention policies?
But let's stick to one table for simplicity and then we can archive or move failed tasks to another table if needed.
However, the problem says "build a persistent work queue", so we are going to design the table for the main queue and then a separate table for the DLQ?
Let me re-read: "persistent work queue with idempotency keys, retries, and DLQs."
I think having two tables is acceptable, but then we have to manage the movement of tasks between them.
Alternatively, we can have:
Table: work_queue
id (primary key)
task_id (unique) -> this is the idempotency key, so must be unique across both tables?
... other fields
Table: dead_letter_queue
id (primary key) (could be the same as work_queue.id? or a new one?)
task_id (unique) -> same as in work_queue?
... other fields (maybe the same as work_queue plus failure reasons)
But then we have two tables and we have to ensure that the same task_id doesn't exist in both at the same time?
Let's think about the lifecycle:
- A task is inserted into work_queue with task_id X.
- A worker picks it up, changes status to processing, and processes.
- If it fails, we increment attempts. If attempts < max_attempts, we put it back to pending (with a backoff) in work_queue.
- If attempts >= max_attempts, we move it to dead_letter_queue.
So the same task_id will only be in one table at a time.
But then when we move from work_queue to dead_letter_queue, we have to delete from work_queue and insert into dead_letter_queue?
Alternatively, we can have a single table with a status field and then we don't need to move data. But then the table will have both pending and failed tasks, which might be okay.
Let me go with a single table:
Table: tasks
id: bigserial primary key
task_id: varchar(255) unique not null, -- the idempotency key provided by the client
payload: jsonb not null,
status: varchar(50) not null, -- 'pending', 'processing', 'completed', 'failed'
attempts: integer not null default 0,
max_attempts: integer not null default 5,
last_error: text,
scheduled_at: timestamp, -- for delayed tasks, if null then ready immediately
created_at: timestamp not null default current_timestamp,
updated_at: timestamp not null default current_timestamp
We can index on:
- task_id (unique)
- status (for querying pending tasks)
- scheduled_at (for scheduling)
But note: we want to avoid duplicate task_id in the table. So if we try to insert a task with the same task_id and it's already in the table (in any status) we should reject?
However, if a task is completed, we might not want to process it again. But what if the client wants to re-run the same task? They might use the same task_id?
Actually, the idempotency key is for a given operation (like a create request) to avoid duplicate processing due to retries of the same request.
So if the same task_id is submitted again, we should check the existing task:
- If the existing task is completed, then we can return the same result? (but we are building a queue, not an API that returns results)
- If the existing task is pending or processing, then we should not insert a new one?
- If the existing task is failed, then we might want to allow re-submission? But then we are going to have the same task_id again?
So maybe we should not have the task_id as unique? But then we break idempotency?
Alternatively, we can have:
- When a task is inserted, if there's already a task with the same task_id and it's in a terminal state (completed or failed) then we can insert a new one?
- But then we are allowing the same task_id to be used multiple times?
Actually, the idempotency key is meant to be unique for a given operation. So if the operation is the same (same task_id) then we should not create a new task if the old one is still active?
But if the old one is completed, then the operation has already been done, so we should not do it again?
However, in a queue, we might want to allow the same task to be run again (for example, a periodic job that runs every day, but we use the same task_id for each run? That doesn't make sense because then the second run would be rejected because the first one is completed).
So perhaps the task_id should be unique only for non-terminal states?
Let me clarify: the idempotency key is for the client to ensure that if they retry the same request (due to network issues) they don't get duplicate processing.
So once a task is completed (or failed and in DLQ) then the client should not retry with the same key?
But in practice, sometimes we want to retry a failed task manually, and then we might use the same task_id?
So maybe we should not enforce uniqueness on task_id? But then we lose the idempotency guarantee for new submissions?
Alternatively, we can have:
- The task_id is unique in the table, but when we move a task to failed (DLQ) we keep it in the same table? Then if we try to insert the same task_id again, we will get a unique constraint violation.
So we have to decide:
Option 1: task_id is unique in the table. Then:
- If a task is completed, we cannot insert the same task_id again.
- If a task is failed, we cannot insert the same task_id again until we delete it from the table?
Option 2: task_id is not unique, but we have a composite unique index on (task_id, status) for non-terminal statuses? That doesn't help.
Option 3: We have two tables: work_queue and dead_letter_queue. In work_queue, task_id is unique (for pending and processing). In dead_letter_queue, we also have task_id but it's not necessarily unique?
But then when we move from work_queue to dead_letter_queue, we delete from work_queue and insert into dead_letter_queue. Then we can insert the same task_id again into work_queue?
However, if we do that, then we break the idempotency because the same task_id can be in work_queue again after being in DLQ?
Actually, the idempotency is about the same request being retried. If the task failed and we want to retry it, that's a new request? Or is it the same request?
In practice, the client might retry the same request (with the same task_id) even after it failed? But then we are going to have two records with the same task_id: one in DLQ and one in work_queue?
That would break the uniqueness of task_id?
So maybe we should not have a unique constraint on task_id at all? Instead, when we try to insert a new task, we check the work_queue for the same task_id and if there's one that is not completed or failed?
But then we have to check both tables?
Let's step back: the idempotency key is for the client to avoid duplicate submission of the same task. So if the client submits a task and it's in the queue (pending or processing) then a duplicate submission should be rejected?
If the task is completed or failed, then the client might want to retry? But then it's a new submission?
Actually, the client should generate a new idempotency key for each new request? But sometimes they might want to retry the same request (with the same key) if the previous one failed?
So the rule should be:
- If there's a task with the same task_id in the work_queue (pending or processing) then reject the new submission (because it's a duplicate of an in-flight task).
- If there's a task with the same task_id in the dead_letter_queue, then we allow the new submission? But then we are creating a new task with the same task_id?
But then we are allowing the same task_id to be used for multiple tasks (one in DLQ and one in work_queue).
Alternatively, we can have:
- When a task is submitted, we check the work_queue for the same task_id. If found and status is pending or processing, then reject.
- If found in work_queue and status is completed, then we can return the result? (but we are a queue, not an API)
- If found in dead_letter_queue, then we allow the new submission?
But then we have to check two tables.
Let's simplify: we keep all tasks in one table, and we have a unique constraint on task_id. Then:
- When a task is completed, we keep it in the table (with status completed) and we cannot insert a new task with the same task_id.
- When a task fails and goes to DLQ, we mark it as failed and we cannot insert a new task with the same task_id.
Then the client cannot retry a failed task with the same task_id?
But then we break the ability to retry?
Alternatively, we can have a separate table for completed tasks?
Let me think of a common pattern:
We have a table for active tasks (pending and processing) and then we have two other tables: completed_tasks and dead_letter_tasks.
Then:
- When a task is submitted, we check the active_tasks table for the same task_id. If exists and is pending/processing, then reject.
- If it exists in completed_tasks or dead_letter_tasks, then we allow? But then we are going to have multiple records with the same task_id in different tables?
That seems acceptable because the active_tasks table only has active tasks, and the other tables are for historical purposes.
But then we have to move tasks between tables:
- When a task is completed, we move it from active_tasks to completed_tasks.
- When a task fails and exceeds max_attempts, we move it from active_tasks to dead_letter_tasks.
And when we retry a failed task, we move it from dead_letter_tasks back to active_tasks?
But then the same task_id will be in active_tasks again, and then we have to check the dead_letter_tasks table when inserting?
Alternatively, we can have:
- active_tasks: unique constraint on task_id (so we cannot have two active tasks with the same task_id).
- dead_letter_tasks: no unique constraint on task_id? But then we can have multiple dead tasks with the same task_id?
But then when we retry, we move from dead_letter_tasks to active_tasks, and that's okay because active_tasks has the unique constraint and we are moving the same task_id?
However, if we want to retry a failed task, we are essentially re-inserting it into active_tasks with the same task_id? But then we have to delete it from dead_letter_tasks?
So the flow:
Insert task:
- If task_id exists in active_tasks and is pending/processing -> reject.
- If task_id exists in dead_letter_tasks -> we can retry? But then we are going to move it to active_tasks? Or create a new active task?
Actually, if we are going to retry, we might want to reset the attempts?
So maybe we have:
active_tasks:
id, task_id, payload, status, attempts, max_attempts, last_error, scheduled_at, created_at, updated_at
dead_letter_tasks:
id, task_id, payload, status (failed), attempts, max_attempts, last_error, created_at, updated_at, moved_to_dlq_at
completed_tasks:
id, task_id, payload, status (completed), attempts, created_at, updated_at, completed_at
Then:
- When a task is first submitted, we insert into active_tasks with status 'pending'.
- When a worker picks it up, it updates the status to 'processing' and sets the attempts to 1 (or increments).
- If the task fails, we increment attempts. If attempts < max_attempts, we update the status to 'pending' and set scheduled_at for backoff.
- If attempts >= max_attempts, we move the task from active_tasks to dead_letter_tasks (delete from active_tasks and insert into dead_letter_tasks).
Now, for retrying a task from the dead_letter_tasks:
- We can have an admin operation that moves a task from dead_letter_tasks back to active_tasks.
- When moving, we reset the attempts to 0? or keep the old attempts? We might want to reset so that it gets max_attempts again?
- But note: the task already failed max_attempts times, so if we reset then it will get max_attempts again?
Alternatively, we can have a separate retry count in dead_letter_tasks?
Actually, the attempts in active_tasks is for the current life cycle. When we move to dead_letter_tasks, we are ending that life cycle.
If we want to retry, we are starting a new life cycle, so we reset attempts to 0?
But then the client might have set max_attempts per task? We keep that.
So when moving from dead_letter_tasks to active_tasks, we set:
status: 'pending'
attempts: 0
last_error: null
scheduled_at: null (or now, if we want to retry immediately)
But then we have to check: what if the same task_id is already in active_tasks? We shouldn't have that because we just moved it from dead_letter_tasks and there's no active task with that task_id?
However, what if someone tries to submit the same task_id again while it's in dead_letter_tasks? We would allow it because we only check active_tasks?
But then we would have two tasks with the same task_id: one in dead_letter_tasks and one in active_tasks?
That breaks the idempotency?
So we must check both active_tasks and dead_letter_tasks?
Alternatively, we can have a global unique constraint on task_id across all tables? But that's not possible in relational databases across tables.
So we have to enforce in application logic:
When inserting a new task (or moving from dead_letter_tasks to active_tasks) we must check:
SELECT 1 FROM active_tasks WHERE task_id = :task_id
UNION
SELECT 1 FROM dead_letter_tasks WHERE task_id = :task_id
If any row exists, then we reject?
But then we cannot retry a failed task because it's in dead_letter_tasks?
So we have to allow the same task_id to be in dead_letter_tasks and then in active_tasks?
But then we break the uniqueness of the task_id?
Actually, the idempotency key is for a given submission. If the task is in dead_letter_tasks, that means it has failed and we consider that submission as failed.
If we want to retry, we are making a new submission (with the same task_id) and that should be allowed?
But then we have two records with the same task_id: one in dead_letter_tasks (the old failed one) and one in active_tasks (the new attempt).
That might be acceptable because they are different attempts?
However, the client might not know that the task has failed and they might retry, and then we have two tasks with the same task_id in the system?
That is exactly what we want to avoid?
Actually, the idempotency key is to avoid duplicate processing of the same submission. If the first submission failed and we are retrying, it's a new submission?
But the client might use the same idempotency key for the retry?
In HTTP, for example, the client might retry the same request with the same Idempotency-Key header. The server should not process the same request twice if the first one completed, but if the first one failed, then the retry is allowed?
But in our queue, we don't have the concept of a completed request that returns a result. We just have tasks.
So let's define:
- The task_id is the idempotency key for a given business operation.
- We want to ensure that the same business operation (same task_id) is not processed more than once at the same time (to avoid duplicates).
- Once a task is completed (or failed and in DLQ) then the business operation is considered done (or failed) and if the client wants to run it again, they should use a new task_id?
But in practice, we might want to retry a failed task with the same task_id?
I think the common practice is: the idempotency key is for a given request. If the request fails (and the task goes to DLQ) then the client can retry with the same key, and we should create a new task?
But then we are creating a new task with the same task_id?
So we cannot have a unique constraint on task_id. Instead, we have to allow multiple tasks with the same task_id, but then we have to decide which one is the one we are going to process?
Actually, we want to avoid having two active tasks (pending or processing) with the same task_id at the same time.
So we can have:
- A unique index on (task_id, status) where status in ('pending', 'processing')?
Then we can have multiple tasks with the same task_id if they are in completed or failed status?
But then when we insert a new task, we check if there's an active task (pending or processing) with the same task_id. If yes, reject.
And when we move a task from dead_letter_tasks to active_tasks, we set status to pending, so we have to check that there's no other active task with the same task_id?
But then we are moving from dead_letter_tasks to active_tasks, and the dead_letter_tasks record has the same task_id?
So we have:
active_tasks:
unique index on (task_id) where status in ('pending', 'processing') -> this means we cannot have two active tasks with the same task_id.
dead_letter_tasks and completed_tasks: no such constraint, so we can have multiple records with the same task_id?
But then when we move from dead_letter_tasks to active_tasks, we are inserting a new active task with the same task_id as the dead_letter_tasks record?
That is allowed because the dead_letter_tasks record is not active.
However, if we want to keep a history of all attempts, we might want to keep the dead_letter_tasks record and then create a new active task?
But then we have two records with the same task_id: one in dead_letter_tasks and one in active_tasks?
That is acceptable because the dead_letter_tasks record is from a previous attempt.
So the flow:
Submit task:
- Check active_tasks for the same task_id and status in ('pending','processing'). If exists, reject.
- Insert into active_tasks with status 'pending'.
Process task:
- Pick an active task with status 'pending' (and scheduled_at <= now) and set status to 'processing' (and update attempts?).
- If the task fails, increment attempts.
- If attempts < max_attempts: set status to 'pending' and set scheduled_at for backoff.
- If attempts >= max_attempts:
- Move the task from active_tasks to dead_letter_tasks (delete from active_tasks and insert into dead_letter_tasks with status 'failed').
- Note: we keep the same task_id and payload, but we don't keep the attempts? We keep the attempts so we know how many times it tried.
Retry from dead_letter_tasks:
- We have to manually move a task from dead_letter_tasks to active_tasks?
- We delete from dead_letter_tasks and insert into active_tasks with status 'pending', attempts=0, and scheduled_at=now?
But then we lose the history of the previous attempts?
Alternatively, we can keep the dead_letter_tasks record and create a new active task? But then we have two active tasks with the same task_id?
We cannot because of the unique index on active_tasks for (task_id) with status in ('pending','processing').
So if we want to retry, we must delete the dead_letter_tasks record?
But then we lose the history.
Alternatively, we can have a separate table for task_attempts?
Given the complexity, maybe we should keep all tasks in one table and have a status field, and then we don't move between tables.
Then we can have:
Table: tasks
id
task_id (with no unique constraint, but we have a composite unique index on (task_id, status) for status in ('pending','processing')?
But then we can have multiple completed tasks with the same task_id?
Actually, we might want to keep a history of all tasks (including completed and failed) and then for active tasks we don't want duplicates.
So:
Table: tasks
id
task_id
payload
status: 'pending', 'processing', 'completed', 'failed'
attempts
max_attempts
last_error
scheduled_at
created_at
updated_at
Indexes:
- On (task_id) where status in ('pending','processing') -> unique?
- On status (for querying pending tasks)
- On scheduled_at (for scheduling)
Then:
When inserting a new task:
- Check if there's a task with the same task_id and status in ('pending','processing'). If yes, reject.
When a task is completed, we set status to 'completed'. Then we can insert a new task with the same task_id? Because the completed task is not in the unique index?
But then we can have multiple completed tasks with the same task_id?
That might be acceptable because we are keeping a history.
When a task fails and goes to DLQ, we set status to 'failed'. Then we can insert a new task with the same task_id?
But then we have a failed task and a new pending task with the same task_id?
That is acceptable because the failed task is not in the unique index.
However, when we retry a failed task, we are going to set the status of the failed task to 'pending'? Or create a new task?
If we are going to retry by updating the failed task, then we set status to 'pending' and reset attempts? But then we are updating the existing row, so we don't have duplicate task_id in active tasks?
But then we lose the history of the previous failure?
Alternatively, we can create a new task for the retry? Then we have two tasks with the same task_id: one failed and one pending?
But then the unique index on (task_id) for status in ('pending','processing') would allow the new pending task, because the failed task is not in that index.
So we can do:
- When retrying, we insert a new task with the same task_id? But then we have two tasks with the same task_id: one failed and one pending?
That breaks the idea of idempotency?
Actually, the idempotency key is for a given submission. If the first submission failed and we are retrying, it's a new submission?
But the client might use the same task_id for the retry?
In that case, we are creating a new task with the same task_id, and the old task is failed.
So we are allowing multiple tasks with the same task_id as long as only one is active (pending or processing) at a time.
This seems acceptable.
So let's go with one table.
Steps:
Table: tasks
id: bigserial primary key
task_id: varchar(255) not null
payload: jsonb not null
status: varchar(50) not null -- 'pending', 'processing', 'completed', 'failed'
attempts: integer not null default 0
max_attempts: integer not null default 5
last_error: text
scheduled_at: timestamp -- for delayed tasks, if null then ready immediately
created_at: timestamp not null default current_timestamp
updated_at: timestamp not null default current_timestamp
Indexes:
CREATE UNIQUE INDEX idx_unique_active_task_id ON tasks (task_id) WHERE status IN ('pending', 'processing');
CREATE INDEX idx_status ON tasks (status);
CREATE INDEX idx_scheduled_at ON tasks (scheduled_at) WHERE status = 'pending' AND scheduled_at IS NOT NULL;
Then:
Inserting a task:
- We do:
INSERT INTO tasks (task_id, payload, status, max_attempts)
VALUES (:task_id, :payload, 'pending', :max_attempts)
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
But note: the unique index only applies to rows with status in ('pending','processing'). So if there's a completed or failed task with the same task_id, the insert will succeed.
Processing a task:
We need to atomically pick a task and mark it as processing. We can do:
UPDATE tasks
SET status = 'processing', attempts = attempts + 1, updated_at = now()
WHERE id = (
SELECT id
FROM tasks
WHERE status = 'pending'
AND (scheduled_at IS NULL OR scheduled_at <= now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING *;
But note: we are updating the same row we select, so we can do:
WITH cte AS (
SELECT id
FROM tasks
WHERE status = 'pending'
AND (scheduled_at IS NULL OR scheduled_at <= now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE tasks
SET status = 'processing', attempts = attempts + 1, updated_at = now()
FROM cte
WHERE tasks.id = cte.id
RETURNING tasks.*;
After processing, if the task succeeds:
UPDATE tasks SET status = 'completed', updated_at = now() WHERE id = :id;
If the task fails:
- If attempts < max_attempts:
UPDATE tasks
SET status = 'pending',
scheduled_at = now() + interval '1 minute' * attempts, -- exponential backoff? or linear?
last_error = :error_message,
updated_at = now()
WHERE id = :id;
- Else:
UPDATE tasks SET status = 'failed', last_error = :error_message, updated_at = now() WHERE id = :id;
But note: the above update for failure with attempts < max_attempts sets scheduled_at to now() + interval. We can do exponential backoff:
scheduled_at = now() + interval '1 minute' * (2 ^ (attempts-1))
However, we are incrementing attempts in the processing update, so when we fail, the attempts have been incremented.
Alternatively, we can do:
attempts = attempts + 1 (when we start processing)
then if fails and attempts < max_attempts:
scheduled_at = now() + interval '1 minute' * (2 ^ (attempts-1))
But note: the first failure is when attempts=1, then backoff = 1 minute, then 2, then 4, etc.
But we are setting scheduled_at when we set the task back to pending.
However, what about the initial scheduled_at? If the task was scheduled for the future, then when we pick it up we set status to processing and then if it fails, we set a new scheduled_at?
That's acceptable.
Now, what about the DLQ? We are marking as 'failed'. We can query the failed tasks and move them to a separate table? Or just leave them in the same table.
Since we have a status, we can just query for status='failed' to get the DLQ.
But if we want to archive the completed and failed tasks, we can move them to separate tables.
However, the requirement says "DLQ", so we can just treat the failed tasks as the DLQ.
But note: we are keeping the failed tasks in the same table. So the table will grow. We might want to delete or archive completed and failed tasks after some time?
That's a separate concern.
So the design:
One table: tasks
Indexes:
- Unique index on (task_id) where status in ('pending','processing')
- Index on status
- Index on scheduled_at (for pending and scheduled_at is not null)
Operations:
-
Submit task:
INSERT INTO tasks (task_id, payload, status, max_attempts)
VALUES (:task_id, :payload, 'pending', :max_attempts)
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
If the insert returns a row, then the task was inserted. If not, then there's already an active task with that task_id.
-
Worker fetch and process:
Step 1: Pick a task (as above with FOR UPDATE SKIP LOCKED) and mark as processing.
Step 2: Process the task.
Step 3a: If success, mark as completed.
Step 3b: If failure:
UPDATE tasks
SET
attempts = attempts + 1, -- we already incremented in step1? Actually, in step1 we set attempts = attempts+1?
status = CASE
WHEN attempts + 1 < max_attempts THEN 'pending'
ELSE 'failed'
END,
scheduled_at = CASE
WHEN attempts + 1 < max_attempts THEN now() + interval '1 minute' * (2 ^ (attempts))
ELSE NULL
END,
last_error = :error_message,
updated_at = now()
WHERE id = :id;
But note: in step1 we set attempts = attempts + 1 and status = 'processing'. So when we update for failure, the attempts have been incremented already?
Let me adjust:
In step1:
SET status = 'processing', attempts = attempts + 1
Then in step3b, we check the current attempts (which is now the old attempts+1). So:
current_attempts = old_attempts + 1
if current_attempts < max_attempts:
set status='pending', scheduled_at = now() + interval '1 minute' * (2 ^ (current_attempts-1))
else:
set status='failed', scheduled_at = NULL
But note: we are updating the same row again.
-
Retry a failed task:
We can do:
UPDATE tasks
SET status = 'pending',
attempts = 0,
scheduled_at = now(),
last_error = NULL,
updated_at = now()
WHERE id = :id AND status = 'failed';
But note: we are resetting the attempts to 0?
Alternatively, we might want to keep the old attempts?
Actually, we are starting a new life cycle, so we reset.
-
Query for DLQ:
SELECT * FROM tasks WHERE status = 'failed';
However, note that the same task_id can have multiple rows: one failed and one pending?
But when we retry, we update the failed row to pending? Then we don't have a failed row for that task_id anymore?
So if we want to keep the history of failures, we should not update the failed row. Instead, we insert a new task?
But then we have two tasks with the same task_id: one failed and one pending?
And the unique index on active tasks (pending and processing) allows that because the failed one is not active.
So we can do:
When retrying, we insert a new task with the same task_id? But then we have to copy the payload?
Alternatively, we can have a separate operation that copies the failed task to a new active task?
But then we have to delete the failed task?
Or we can leave the failed task and insert a new one?
Then we have two records with the same task_id: one failed and one pending?
That is acceptable.
But then when we insert a new task (for retry) we have to check that there's no active task with the same task_id. We do that with the unique index.
So the retry operation would be:
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE id = :id AND status = 'failed'
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
But then we are not resetting the attempts? The new task will have attempts=0.
And we leave the old failed task as is.
That keeps the history.
But then we have two tasks with the same task_id: one failed and one pending.
That is acceptable.
However, if we want to retry multiple times, we will have multiple failed tasks?
Actually, we are only inserting a new active task. The old failed tasks remain.
So the history of failures is kept.
But note: the client might retry the same task_id multiple times, and then we will have multiple failed tasks and one active task?
That's acceptable.
So the design:
- One table: tasks
- Unique index on (task_id) for status in ('pending','processing')
- When inserting a new task (or retry) we check that there's no active task with the same task_id.
This ensures that we don't have two active tasks with the same task_id.
Now, what about the case where a task is completed and then we want to run it again?
We can insert a new task with the same task_id? Because the completed task is not active.
But then we have two tasks with the same task_id: one completed and one pending?
That is acceptable.
However, the client might not know that the task was completed and they might retry, and then we have two records?
But that's the client's responsibility: they should generate a new idempotency key for each new request?
Actually, the idempotency key is for a given request. If the request is to run a task that has already been completed, then it's a new request?
So we are allowing it.
But then we might process the same business operation multiple times?
That's a business logic issue. The queue doesn't know about the business operation. It just processes tasks.
So the client should use a new idempotency key for each new request?
But if they use the same key for a completed task, we will allow it?
Yes, because the completed task is not active.
So the idempotency is only for in-flight tasks.
This is a common pattern: idempotency keys are only checked against in-flight (or recently completed) requests?
Actually, in HTTP, the idempotency key is stored for a certain period (like 24 hours) and then removed?
But in our queue, we are storing all tasks forever?
We might want to prune old completed and failed tasks?
That's a separate concern.
So let's stick to:
- We have one table: tasks.
- We have a unique index on (task_id) for status in ('pending','processing').
- We allow multiple tasks with the same task_id if they are in completed or failed status.
This gives us:
- Idempotency for in-flight tasks (pending and processing).
- Retries by inserting a new task (or updating a failed task to pending? but then we lose the failure history).
- We choose to insert a new task for retry to keep the history.
But then when we retry, we are inserting a new task with the same task_id. The old failed task remains.
So the DLQ is just the set of tasks with status='failed'.
Now, let's write the SQL for the table and indexes.
We'll use PostgreSQL syntax.
Table:
CREATE TABLE tasks (
id BIGSERIAL PRIMARY KEY,
task_id VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(50) NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
last_error TEXT,
scheduled_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Indexes:
CREATE UNIQUE INDEX idx_unique_active_task_id ON tasks (task_id) WHERE status IN ('pending', 'processing');
CREATE INDEX idx_status ON tasks (status);
CREATE INDEX idx_scheduled_at ON tasks (scheduled_at) WHERE status = 'pending' AND scheduled_at IS NOT NULL;
We also might want an index on created_at for ordering?
But the worker uses ORDER BY created_at, so:
CREATE INDEX idx_created_at ON tasks (created_at) WHERE status = 'pending';
However, note that we are also filtering by scheduled_at. We might want a composite index:
CREATE INDEX idx_pending_scheduled ON tasks (scheduled_at, created_at) WHERE status = 'pending';
But then if scheduled_at is null, we want to order by created_at?
Alternatively, we can do:
WHERE status = 'pending' AND (scheduled_at IS NULL OR scheduled_at <= now())
And then order by created_at.
We can have an index on (status, scheduled_at, created_at) but with a condition that scheduled_at is not null?
Actually, we want to get pending tasks that are ready (scheduled_at is null or scheduled_at <= now()).
We can create an index on (status, scheduled_at) where status='pending' and scheduled_at is not null, and then also have an index on (status) for pending tasks without scheduled_at?
But the query might be:
SELECT ... FROM tasks
WHERE status='pending'
AND (scheduled_at IS NULL OR scheduled_at <= now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1;
We can try:
CREATE INDEX idx_pending_scheduled_created ON tasks (status, scheduled_at, created_at)
WHERE status = 'pending' AND scheduled_at IS NOT NULL;
And then for the ones with scheduled_at null, we can have:
CREATE INDEX idx_pending_created ON tasks (status, created_at)
WHERE status = 'pending' AND scheduled_at IS NULL;
But then the query would use both indexes?
Alternatively, we can have:
CREATE INDEX idx_pending_scheduled_created ON tasks (status, scheduled_at, created_at)
WHERE status = 'pending';
This index will include rows with scheduled_at null? In PostgreSQL, nulls are allowed and they are considered equal? Actually, in B-tree indexes, nulls are not equal, so they are stored separately?
But the condition (scheduled_at IS NULL OR scheduled_at <= now()) would not be efficiently supported by one index?
We can do:
We have two indexes:
Index 1: for pending tasks with scheduled_at null:
CREATE INDEX idx_pending_null_scheduled ON tasks (status, created_at)
WHERE status = 'pending' AND scheduled_at IS NULL;
Index 2: for pending tasks with scheduled_at not null:
CREATE INDEX idx_pending_not_null_scheduled ON tasks (status, scheduled_at, created_at)
WHERE status = 'pending' AND scheduled_at IS NOT NULL;
Then the query can use both indexes with a UNION?
But the query optimizer might choose one index and then filter the other condition?
Alternatively, we can have one expression index:
CREATE INDEX idx_pending_ready ON tasks (status,
CASE
WHEN scheduled_at IS NULL THEN 0
ELSE 1
END,
COALESCE(scheduled_at, '1970-01-01'),
created_at)
WHERE status = 'pending';
This way, we order by the case: first the ones with scheduled_at null (0) then the ones with scheduled_at not null (1) and then by scheduled_at and created_at?
But we want to get the tasks that are ready: scheduled_at is null or scheduled_at <= now().
We cannot put the condition scheduled_at <= now() in the index because it's a variable.
So we index on scheduled_at and then the query condition will filter by scheduled_at <= now().
So the index:
CREATE INDEX idx_pending_ready ON tasks (status, scheduled_at, created_at)
WHERE status = 'pending';
Then the query:
WHERE status='pending' AND (scheduled_at IS NULL OR scheduled_at <= now())
The index can be used for the status and the scheduled_at condition (for the not null part) and then we have to filter the nulls?
Actually, the index will have all pending tasks, and then we filter by scheduled_at <= now() and scheduled_at is null.
The index can be used for the range condition on scheduled_at, but the nulls are not in the index?
Wait, the index includes nulls? In PostgreSQL, B-tree indexes do include nulls. So the index will have rows with scheduled_at null.
Then the condition (scheduled_at IS NULL OR scheduled_at <= now()) can be satisfied by the index?
We can do:
WHERE status='pending' AND (scheduled_at IS NULL OR scheduled_at <= now())
The index on (status, scheduled_at, created_at) can be used for:
- status = 'pending'
- and then for the scheduled_at condition: it can do an index scan on scheduled_at for the range (scheduled_at <= now()) and also include the nulls?
But the condition is OR, so the index might not be used efficiently.
Alternatively, we can rewrite the query as:
WHERE status='pending'
AND (scheduled_at IS NULL
OR scheduled_at <= now())
This is the same.
We can try to create two indexes and use UNION?
But let's keep it simple and have:
CREATE INDEX idx_pending_scheduled ON tasks (status, scheduled_at) WHERE status = 'pending';
And then order by created_at?
Actually, we need to order by created_at, so we include created_at in the index.
Let's create:
CREATE INDEX idx_pending_scheduled_created ON tasks (status, scheduled_at, created_at)
WHERE status = 'pending';
Then the query:
SELECT * FROM tasks
WHERE status='pending'
AND (scheduled_at IS NULL OR scheduled_at <= now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1;
The index can be used for the status and the scheduled_at condition (for the not null part) and then we have to filter the nulls?
Actually, the index will have all pending tasks with scheduled_at (including null).
The condition scheduled_at <= now() will be applied to the index, and the nulls will be included because they are in the index?
But the condition is OR, so the planner might choose to do an index scan on scheduled_at for the range and then also fetch the nulls?
Alternatively, we can do:
(SELECT * FROM tasks
WHERE status='pending' AND scheduled_at IS NULL
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1)
UNION ALL
(SELECT * FROM tasks
WHERE status='pending' AND scheduled_at <= now()
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1)
LIMIT 1;
But that's two queries.
Given the complexity, we can start with one index and see the performance.
Alternatively, we can have a computed column that is the next run time, and then index on that?
Let's define:
next_run_at = COALESCE(scheduled_at, created_at)
Then we want tasks where next_run_at <= now().
Then we can create an index on (status, next_run_at, created_at) where status='pending'.
But then we have to maintain the computed column?
We can do:
ALTER TABLE tasks ADD COLUMN next_run_at TIMESTAMP
GENERATED ALWAYS AS (COALESCE(scheduled_at, created_at)) STORED;
Then:
CREATE INDEX idx_pending_next_run ON tasks (status, next_run_at, created_at)
WHERE status = 'pending';
Then the query:
SELECT * FROM tasks
WHERE status='pending'
AND next_run_at <= now()
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1;
This is simpler.
So let's do:
Table tasks with next_run_at as a generated column.
But note: if we update scheduled_at, then next_run_at will update automatically?
Yes, if it's stored.
So:
CREATE TABLE tasks (
id BIGSERIAL PRIMARY KEY,
task_id VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(50) NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
last_error TEXT,
scheduled_at TIMESTAMP,
next_run_at TIMESTAMP GENERATED ALWAYS AS (COALESCE(scheduled_at, created_at)) STORED,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Then:
CREATE UNIQUE INDEX idx_unique_active_task_id ON tasks (task_id) WHERE status IN ('pending', 'processing');
CREATE INDEX idx_status ON tasks (status);
CREATE INDEX idx_pending_next_run ON tasks (status, next_run_at, created_at) WHERE status = 'pending';
Now the worker query:
WITH cte AS (
SELECT id
FROM tasks
WHERE status = 'pending'
AND next_run_at <= now()
ORDER BY next_run_at, created_at -- we want the one that is ready the longest?
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE tasks
SET status = 'processing',
attempts = attempts + 1,
updated_at = now()
FROM cte
WHERE tasks.id = cte.id
RETURNING tasks.*;
But note: we are ordering by next_run_at and then created_at?
We can adjust the order as needed.
Now, the backoff:
When we fail and retry (attempts < max_attempts), we set scheduled_at to now() + interval.
We can do:
scheduled_at = now() + interval '1 minute' * (2 ^ (attempts-1))
But note: attempts have been incremented in the processing step.
So in the failure update:
SET scheduled_at = now() + interval '1 minute' * (2 ^ (attempts-1))
But what if attempts is 0? Then we get 2^(-1) which is 0.5?
Actually, when we first process, attempts becomes 1. Then if it fails, we set scheduled_at for the next retry.
So:
attempts after processing = 1 -> then set scheduled_at for next_run = now() + 1 minute.
Then if it fails again, attempts=2 -> now() + 2 minutes?
But we want exponential: 1, 2, 4, 8, ...
So:
scheduled_at = now() + interval '1 minute' * (2 ^ (attempts-1))
For attempts=1: 2^(0)=1 -> 1 minute.
For attempts=2: 2^(1)=2 -> 2 minutes.
For attempts=3: 2^(2)=4 -> 4 minutes.
That's exponential.
Alternatively, we can do:
scheduled_at = now() + interval '1 minute' * (2 ^ attempts)
But then for attempts=1: 2 minutes?
We are incrementing attempts in the processing step, so when we fail the first time, attempts=1.
So we want the first retry after 1 minute? Then use (2^(attempts-1)).
But note: if we set the initial scheduled_at for delayed tasks, then we don't use the backoff formula.
So the backoff is only for retries after a failure.
Now, the code for the worker:
Step 1: Fetch and lock a task (as above).
Step 2: Process the task.
Step 3: If success, update to completed.
Step 4: If failure:
UPDATE tasks
SET
attempts = attempts + 1, -- but we already incremented in step1? Actually, in step1 we set attempts = attempts+1. So we don't need to do it again.
status = CASE
WHEN attempts < max_attempts THEN 'pending'
ELSE 'failed'
END,
scheduled_at = CASE
WHEN attempts < max_attempts THEN now() + interval '1 minute' * (2 ^ (attempts-1))
ELSE NULL
END,
last_error = :error_message,
updated_at = now()
WHERE id = :id;
But wait: in step1, we set attempts = attempts + 1 and status = 'processing'. So in step4, the attempts have been incremented.
So the condition should be:
current_attempts = attempts (which is old_attempts+1)
if current_attempts < max_attempts:
set status='pending', scheduled_at = now() + interval '1 minute' * (2 ^ (current_attempts-1))
else:
set status='failed'
So:
UPDATE tasks
SET
status = CASE
WHEN attempts < max_attempts THEN 'pending'
ELSE 'failed'
END,
scheduled_at = CASE
WHEN attempts < max_attempts THEN now() + interval '1 minute' * (2 ^ (attempts-1))
ELSE NULL
END,
last_error = :error_message,
updated_at = now()
WHERE id = :id;
But note: we are not updating attempts again? We already updated in step1.
So we are good.
However, what if the task was already at max_attempts? Then we set status to 'failed' and scheduled_at to null.
Now, what about the case where we want to retry a failed task?
We can do:
UPDATE tasks
SET status = 'pending',
attempts = 0,
scheduled_at = now(),
last_error = NULL,
updated_at = now()
WHERE id = :id AND status = 'failed';
But note: this updates the existing failed task. We lose the failure history?
We are setting attempts to 0 and removing the last_error?
But the task is now pending again, and if it fails again, we will set attempts=1, then 2, etc.
And we have the history of the previous failures?
We don't, because we reset the attempts and last_error.
So if we want to keep the history, we should insert a new task?
But then we have to copy the payload and set task_id?
And then we have two tasks with the same task_id: one failed and one pending?
That is acceptable.
So we can have two ways:
Option A: Update the failed task (lose history of that failure, but we have the current attempts reset to 0).
Option B: Insert a new task (keep the old failed task, and have a new pending task with the same task_id).
Which one to choose?
If we want to keep the history of all attempts (including the ones that failed and then retried) then we should insert a new task?
But then we have multiple tasks with the same task_id.
And the client might have set max_attempts for the task? We are using the same max_attempts?
We can copy the max_attempts from the failed task.
So:
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE id = :id AND status = 'failed'
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
This will insert a new task with the same task_id and payload, and the same max_attempts.
But note: the failed task might have had a different payload? No, the payload is the same.
So we are creating a new attempt.
This way we keep the old failed task and have a new pending task.
Then, when the new task completes (or fails) we will have:
- The old failed task (status='failed')
- The new task: either completed or failed.
So we have a history.
I think this is better.
But then we have to decide: when we insert a new task for retry, we are using the same task_id?
Yes.
And the unique index on active tasks (pending and processing) will allow it because the old task is failed and not active.
So we are good.
Now, what about the case where we want to retry a task that is already in the DLQ (failed) and we want to reset the attempts?
We are creating a new task with attempts=0.
So the new task will get a fresh set of max_attempts.
That is acceptable.
Now, what about the case where we want to cancel a task?
We can update the status to 'cancelled'? But then we have to define a new status.
Let's leave that for now.
So the summary:
Table: tasks
id, task_id, payload, status, attempts, max_attempts, last_error, scheduled_at, next_run_at, created_at, updated_at
Indexes:
- Unique on (task_id) where status in ('pending','processing')
- On (status, next_run_at, created_at) where status='pending'
Operations:
1. Submit:
INSERT ... ON CONFLICT DO NOTHING.
2. Worker fetch:
WITH cte AS ( ... ) UPDATE ... RETURNING.
3. On success:
UPDATE tasks SET status='completed', updated_at=now() WHERE id=:id;
4. On failure:
UPDATE tasks
SET status = CASE WHEN attempts < max_attempts THEN 'pending' ELSE 'failed' END,
scheduled_at = CASE WHEN attempts < max_attempts THEN now() + interval '1 minute' * (2 ^ (attempts-1)) ELSE NULL END,
last_error = :error,
updated_at = now()
WHERE id = :id;
5. Retry a failed task:
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE id = :id AND status = 'failed'
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
6. Query DLQ:
SELECT * FROM tasks WHERE status = 'failed';
But note: the retry operation might fail if there's already an active task with the same task_id?
Yes, because we have the unique index on active tasks. So if there's already a pending or processing task with the same task_id, we cannot insert a new one.
That's by design.
Now, what about the case where we want to retry a task that is already pending?
We shouldn't, because it's already in the queue.
So the retry operation is only for failed tasks.
But what if we want to retry a completed task?
We can do the same: insert a new task with the same task_id?
But then we have a completed task and a pending task with the same task_id?
That is acceptable.
But the client might not want that?
We can leave that to the client.
So the retry operation is only for failed tasks?
We can have a general "requeue" operation that takes a task_id and inserts a new task if the old one is in a terminal state (failed or completed)?
But then we are allowing the same task_id to be run multiple times?
That's the client's decision.
We can provide an API to requeue a task by id (from the tasks table) that:
- If the task is failed or completed, then insert a new task with the same task_id and payload.
- If the task is pending or processing, then do nothing?
But then we are allowing multiple completed tasks with the same task_id?
Yes.
So we can have:
requeue_task(task_id):
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE task_id = :task_id
AND status IN ('failed', 'completed')
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
But note: we are using task_id to find the old task, and then we insert a new task with the same task_id.
But what if there are multiple failed tasks with the same task_id?
Then we will insert multiple new tasks?
We only want to insert one?
Actually, we want to requeue the latest? Or any?
We can pick the latest (by created_at) failed or completed task?
But then we are only inserting one new task.
Alternatively, we can requeue all?
That might not be intended.
So let's say we requeue the latest failed or completed task?
But then we have to order by created_at and limit 1?
But we are inserting only one.
Alternatively, we can requeue by the task's id (the primary key).
So we can have an endpoint that takes the task's id (the primary key) and then inserts a new task with the same task_id and payload.
So:
requeue_task_by_id(old_task_id):
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE id = :old_task_id
AND status IN ('failed', 'completed')
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
This way we only requeue that specific task.
Now, what about the case where we want to cancel a task?
We can add a status 'cancelled' and then update the task to cancelled?
But then we have to make sure the worker doesn't pick it up.
So we can update the status to 'cancelled' and then the worker query will not pick it because status='pending' only.
But what if the task is already processing?
We can update it to 'cancelled' but the worker might have already picked it?
Then we have to have a way to interrupt the worker? That's out of scope.
So we can only cancel pending tasks?
We can update the status to 'cancelled' for a pending task, and then it won't be picked.
So:
UPDATE tasks SET status='cancelled', updated_at=now() WHERE id=:id AND status='pending';
But then we lose the scheduled_at?
We don't care because it's cancelled.
Now, what about the DLQ?
We have status='failed' for the DLQ.
We might want to have a separate table for the DLQ to archive?
But we can just query by status.
However, if we have a lot of tasks, we might want to move the completed and failed tasks to history tables?
We can do:
CREATE TABLE tasks_history (LIKE tasks INCLUDING ALL);
Then periodically move completed and failed tasks older than X days to tasks_history and delete from tasks.
But then we have to adjust the unique index?
The unique index is only for active tasks, so when we move to history we don't need that index.
So we can:
INSERT INTO tasks_history
SELECT * FROM tasks
WHERE status IN ('completed','failed')
AND updated_at < now() - interval '30 days';
DELETE FROM tasks
WHERE status IN ('completed','failed')
AND updated_at < now() - interval '30 days';
But then we have to make sure that we don't have active tasks with the same task_id in the history?
Actually, the history table doesn't have the unique index, so we can have multiple tasks with the same task_id in the history.
That's acceptable.
But note: the history table might have a task with the same task_id as an active task?
Yes, because the active task is in the tasks table and the history task is in the history table.
And when we check for active tasks, we only check the tasks table.
So that's acceptable.
However, if we want to requeue a task from history?
We would have to move it back?
We can do:
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks_history
WHERE id = :history_task_id
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
But then we have the same task_id in both tables?
That's acceptable.
So the history table is just for archival.
Now, let's write the complete SQL for the tables and indexes.
We'll create:
Table: tasks
Table: tasks_history (if we want to archive)
But let's not create the history table for now, because it's an optimization.
So the minimal design:
CREATE TABLE tasks (
id BIGSERIAL PRIMARY KEY,
task_id VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(50) NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
last_error TEXT,
scheduled_at TIMESTAMP,
next_run_at TIMESTAMP GENERATED ALWAYS AS (COALESCE(scheduled_at, created_at)) STORED,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX idx_unique_active_task_id ON tasks (task_id) WHERE status IN ('pending', 'processing');
CREATE INDEX idx_status ON tasks (status);
CREATE INDEX idx_pending_next_run ON tasks (status, next_run_at, created_at) WHERE status = 'pending';
We might also want an index on (task_id) for the requeue and delete operations?
But we are using the primary key for most operations.
Now, let's consider the worker concurrency:
We use FOR UPDATE SKIP LOCKED to avoid multiple workers picking the same task.
But note: we are updating the same row we select, so we are locking it.
The CTE with FOR UPDATE SKIP LOCKED will lock the row and then we update it.
This is safe.
However, if we have multiple workers, they will each pick a different row (because of SKIP LOCKED).
Now, what about the backoff?
We are setting scheduled_at for the next run. But note: if a task fails and we set scheduled_at to 1 minute in the future, then it won't be picked until then.
But what if we have many tasks and they all fail at the same time? Then they all get scheduled for the same time?
We are using exponential backoff based on the number of attempts, so they will be spread out.
However, we are ordering by next_run_at and then created_at. So the one with the earliest next_run_at will be picked first.
But if multiple tasks have the same next_run_at, then we order by created_at.
That's acceptable.
Now, what about the case where a task is stuck in processing?
We don't have a way to reset it?
We can have a cron job that checks for tasks in processing for too long and resets them to pending?
But that's a separate concern.
So the design is complete.
Let me write the SQL for the table and indexes.
We'll also add a trigger to update updated_at?
We can do:
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
CREATE TRIGGER update_tasks_updated_at
BEFORE UPDATE ON tasks
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at();
But we are setting updated_at in the updates, so we don't need the trigger?
We are setting updated_at in every update, so we can skip the trigger.
But if we forget to set updated_at in an update, then it won't be updated.
So we can use the trigger to be safe.
Alternatively, we can set updated_at in the trigger and then not set it in the queries?
Let's use the trigger.
So:
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ language 'plpgsql';
CREATE TRIGGER update_tasks_updated_at
BEFORE UPDATE ON tasks
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at();
Then in our update queries, we don't set updated_at.
But note: we are setting scheduled_at and last_error and status and attempts. We want updated_at to be set to now().
So we can remove the updated_at from the update statements and rely on the trigger.
Let's adjust the queries:
Worker fetch:
WITH cte AS (
SELECT id
FROM tasks
WHERE status = 'pending'
AND next_run_at <= now()
ORDER BY next_run_at, created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE tasks
SET status = 'processing',
attempts = attempts + 1
FROM cte
WHERE tasks.id = cte.id
RETURNING tasks.*;
Then the failure update:
UPDATE tasks
SET
status = CASE
WHEN attempts < max_attempts THEN 'pending'
ELSE 'failed'
END,
scheduled_at = CASE
WHEN attempts < max_attempts THEN now() + interval '1 minute' * (2 ^ (attempts-1))
ELSE NULL
END,
last_error = :error_message
WHERE id = :id;
The trigger will set updated_at.
Similarly, the success update:
UPDATE tasks SET status='completed' WHERE id=:id;
And the retry insert:
INSERT INTO tasks (task_id, payload, status, max_attempts)
SELECT task_id, payload, 'pending', max_attempts
FROM tasks
WHERE id = :id AND status = 'failed'
ON CONFLICT (task_id) WHERE status IN ('pending','processing') DO NOTHING
RETURNING *;
The insert will set created_at and updated_at to current_timestamp by default.
Now, what about the cancel?
UPDATE tasks SET status='cancelled' WHERE id=:id AND status='pending';
This will set updated_at by trigger.
Now, let's write the complete SQL script.
We assume PostgreSQL.
We'll create the table, indexes, and trigger.
We might also want to add a constraint to ensure that status is one of the allowed values?
We can use a check constraint:
ALTER TABLE tasks ADD CONSTRAINT tasks_status_check CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled'));
But we are using 'cancelled'? We didn't use it in the index.
We can add it.
Let's do:
CREATE TABLE tasks (
id BIGSERIAL PRIMARY KEY,
task_id VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(50) NOT NULL CHECK (status IN ('pending', 'processing', 'completed', 'failed', 'cancelled')),
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
last_error TEXT,
scheduled_at TIMESTAMP,
next_run_at TIMESTAMP GENERATED ALWAYS AS (COALESCE(scheduled_at, created_at)) STORED,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Then the indexes:
CREATE UNIQUE INDEX idx_unique_active_task_id ON tasks (task_id) WHERE status IN ('pending', 'processing');
CREATE INDEX idx_status ON tasks (status);
CREATE INDEX idx_pending_next_run ON tasks (status, next_run_at, created_at) WHERE status = 'pending';
And the trigger for updated_at.
Now, note: the generated column next_run_at uses created_at, which is set on insert. So it will be the created_at if scheduled_at is null.
This is correct.
Now, we have to consider: what if we update the scheduled_at? Then next_run_at will update accordingly.
That's what we want.
This design should work.
However, note that the unique index on active tasks (task_id) will allow multiple tasks with the same task_id if they are in completed, failed, or cancelled status.
And the worker only picks pending tasks.
So we are good.
Let me write the SQL script.</think>