Claiming a job in DynamoDB
SQS can deliver the same message more than once. A DynamoDB conditional update lets one worker claim the job. Also covers failed claims and reclaiming a stuck row after a crash.
This post explains how to claim a job in Amazon DynamoDB. A claim is a row update that only one worker can win.
Amazon SQS will sometimes deliver the same cover job twice. Visibility timeout hides a message. It is not a lock. Two workers can both download the original, both run Sharp, and both write the WebP. You waste CPU. If completion also sends email or increments a counter, you double those side effects.
DynamoDB conditional writes give you a lock that SQS cannot. You store one item per cover. A worker may start pixel work only if it wins an update: status must still be stored. The other worker skips the job.
This post covers UpdateItem with a condition, ConditionalCheckFailedException, and how to reclaim a row stuck in working after a crash.
What a claim is
A claim is an atomic update. Atomic means DynamoDB applies the change only if a condition is still true on the latest item. Two workers can call the same update at the same time. One succeeds. The other gets an error.
The error name is ConditionalCheckFailedException. It means another worker already claimed the job. It is not a crash. Return false and skip.
You do not lock the SQS message. You lock a row in a table. The queue still wakes workers. The table records who may resize.
Why DynamoDB is used with SQS
SQS is a trigger. DynamoDB stores the current status for that cover.
status | meaning |
|---|---|
| original is in S3, nobody has claimed the resize |
| one worker owns the resize right now |
| derivative is in S3 |
The upload handler writes the item as stored after PutObject, then enqueues. The worker reads the item, tries to move stored to working, resizes, then moves working to ready.
status is a reserved word in DynamoDB expressions. You refer to it as #status in UpdateExpression and ConditionExpression, and map #status to status in ExpressionAttributeNames. A typo like SET $status is not a valid update. Use #status.
Sunday Pantry is a small recipe website that stores cover photos. The queue message says “resize this cover.” The table row says whether that cover is still free, already in progress, or done. Two workers can hold copies of the same SQS message. Only one can change stored to working.
A small example
One partition key: id (the coverId). On-demand billing is enough for a journal traffic pattern. The official billing mode name is PAY_PER_REQUEST.
The first snippet creates the table and writes the stored row. Later snippets claim the row, mark it ready, and reclaim a stale working row after a crash.
How it works
Create the table and the first row
import {
CreateTableCommand,
DynamoDBClient,
PutItemCommand,
} from "@aws-sdk/client-dynamodb";
const dynamodb = new DynamoDBClient({ region: "us-east-1" });
const TABLE = "pantry-covers";
const ensureCoversTable = async () => {
try {
await dynamodb.send(
new CreateTableCommand({
TableName: TABLE,
KeySchema: [{ AttributeName: "id", KeyType: "HASH" }],
AttributeDefinitions: [
{ AttributeName: "id", AttributeType: "S" },
],
BillingMode: "PAY_PER_REQUEST",
}),
);
} catch (error: unknown) {
if (
error &&
typeof error === "object" &&
"name" in error &&
error.name === "ResourceInUseException"
) {
return;
}
throw error;
}
};
const recordStoredCover = async (cover: {
id: string;
originalKey: string;
filename: string;
contentType: string;
}) => {
const now = new Date().toISOString();
await dynamodb.send(
new PutItemCommand({
TableName: TABLE,
Item: {
id: { S: cover.id },
status: { S: "stored" },
originalKey: { S: cover.originalKey },
filename: { S: cover.filename },
contentType: { S: cover.contentType },
createdAt: { S: now },
updatedAt: { S: now },
}),
}),
);
};ensureCoversTable creates pantry-covers with a string partition key named id. ResourceInUseException means the table already exists. Catch that on boot so a second process does not crash. Any other error is rethrown.
recordStoredCover writes one item. Attribute values use the DynamoDB low-level shape: { S: "..." } for strings. Status starts as stored. Timestamps are ISO-8601 strings. Call this after the S3 upload and before SendMessage. The worker will look up id from the job JSON.
Claim the job
UpdateItem with a condition is atomic. DynamoDB applies the update only if the condition is true against the latest item.
import { GetItemCommand, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
const loadCover = async (id: string) => {
const result = await dynamodb.send(
new GetItemCommand({
TableName: TABLE,
Key: { id: { S: id } },
}),
);
return result.Item;
};
const claimCover = async (id: string) => {
const now = new Date().toISOString();
try {
await dynamodb.send(
new UpdateItemCommand({
TableName: TABLE,
Key: { id: { S: id } },
UpdateExpression: "SET #status = :working, updatedAt = :now",
ConditionExpression: "#status = :stored",
ExpressionAttributeNames: { "#status": "status" },
ExpressionAttributeValues: {
":stored": { S: "stored" },
":working": { S: "working" },
":now": { S: now },
},
}),
);
return true;
} catch (error: unknown) {
if (
error &&
typeof error === "object" &&
"name" in error &&
error.name === "ConditionalCheckFailedException"
) {
return false;
}
throw error;
}
};loadCover reads the item by id. You will use that read to skip work that is already ready.
claimCover tries to set #status to working only if it is still stored. #status maps to the real attribute name status through ExpressionAttributeNames. Placeholders like :stored and :working are values, not names.
If two workers call claimCover together, one succeeds and returns true. The other gets ConditionalCheckFailedException and returns false. That is “someone else has it,” not a crash.
A failed condition still consumes write capacity based on the existing item size. For this table that cost is small. Do not retry a failed claim as if it were a network error.
Mark the cover ready
After Sharp and the processed PutObject:
const markCoverReady = async (id: string) => {
const now = new Date().toISOString();
await dynamodb.send(
new UpdateItemCommand({
TableName: TABLE,
Key: { id: { S: id } },
UpdateExpression: "SET #status = :ready, updatedAt = :now",
ConditionExpression: "#status = :working",
ExpressionAttributeNames: { "#status": "status" },
ExpressionAttributeValues: {
":working": { S: "working" },
":ready": { S: "ready" },
":now": { S: now },
},
}),
);
};This update only runs if the row is still working. That keeps a stray process from overwriting a cover that already finished.
If the item is already ready, a duplicate SQS delivery should load the item, see ready, and return without claiming. Delete the SQS message. Do not run Sharp again.
const processCoverMessage = async (body: string) => {
const job = JSON.parse(body) as { coverId: string };
const item = await loadCover(job.coverId);
if (!item) {
throw new Error(`No cover row for ${job.coverId}`);
}
if (item.status?.S === "ready") {
return;
}
const claimed = await claimCover(job.coverId);
if (!claimed) {
return;
}
await resizeAndUploadCover(job);
await markCoverReady(job.coverId);
};Parse the job JSON and load the row. A missing row is a real failure: throw so SQS retries, and eventually the dead-letter queue from the previous post.
If status is already ready, return. Returning without a throw means “done or not ours.” Delete the SQS message.
If claimCover returns false, another worker owns the job. Return and delete the duplicate message.
If the claim succeeds, resize, then mark ready. Throwing before delete keeps the SQS retry (and eventually the dead-letter queue).
Reclaim a stale working row
If a worker claims, then dies, the row stays working. Other workers skip. The cover never becomes ready.
After a grace period (two minutes is a reasonable start for an 800 px resize), allow a steal: update updatedAt only if status is still working and updatedAt is older than the cutoff.
const reclaimStaleCover = async (id: string, staleBefore: string) => {
const now = new Date().toISOString();
try {
await dynamodb.send(
new UpdateItemCommand({
TableName: TABLE,
Key: { id: { S: id } },
UpdateExpression: "SET updatedAt = :now",
ConditionExpression:
"#status = :working AND updatedAt < :staleBefore",
ExpressionAttributeNames: { "#status": "status" },
ExpressionAttributeValues: {
":working": { S: "working" },
":staleBefore": { S: staleBefore },
":now": { S: now },
},
}),
);
return true;
} catch (error: unknown) {
if (
error &&
typeof error === "object" &&
"name" in error &&
error.name === "ConditionalCheckFailedException"
) {
return false;
}
throw error;
}
};The condition requires both working and an old updatedAt. ISO-8601 timestamps compare as strings when they share the same format. The worker that wins the reclaim then runs Sharp and calls markCoverReady.
If the original worker is still running, you can get two resizes. Keep the derivative key deterministic (web/${coverId}.webp) so the last write wins. Avoid side effects that cannot be repeated, such as sending email, until ready.
The full path looks like this:
- Upload writes S3, a DynamoDB row in
stored, and an SQS message. - A worker receives the message (maybe twice).
- Conditional claim: at most one
storedtoworking. - Resize,
workingtoready, delete the SQS message. - A duplicate message sees
readyand leaves. - Crash after claim: stale reclaim after two minutes.
SQS still retries transport and process failures. DynamoDB still stops the duplicate happy path.
Common mistakes
Updating without a condition. Both workers set working. You lost the lock.
Catching every error as a failed claim. A real ValidationException (bad expression) must surface. Only ConditionalCheckFailedException means “lost the race.”
Using SET $status. Dollar signs are not expression attribute names. Use #status plus ExpressionAttributeNames.
Reclaiming without a time check. Any working row would be stealable immediately. Two live workers would fight.
Treating DynamoDB as the queue. Scanning stored items in a loop is a second, worse queue. Keep SQS as the wakeup.
GetItem then decide in memory without a condition on the write. Two workers can both see stored and both proceed. The condition on UpdateItem is the lock. The GetItem is only a shortcut for ready.
When you do not need this
If you have one worker process, and you accept a rare double Sharp run on SQS duplicates, you can skip the table. The moment you run two consumers, or you show status in the UI, store the row.
The app-owned pipeline is now complete: S3 original, SQS job, dead-letter queue, DynamoDB claim, WebP output. The next posts switch shape: the browser uploads to S3 itself, and AWS starts the worker.
Further reading
- Working with items and attributes in DynamoDB –
GetItem,PutItem,UpdateItem, conditional writes - DynamoDB condition expressions –
ConditionExpressionand failed requests - Previous: SQS dead-letter queues
- Next: Presigned URLs for S3 uploads
Related posts
- Two AWS designs for an image pipeline
A comparison of a Node.js worker you run yourself and a setup with presigned uploads plus Lambda. What each design includes, and how to choose.
- Processing SQS messages with Lambda
How Lambda receives messages from SQS, parses the nested S3 event, resizes the image, and writes to another bucket. Also batches, timeouts, and Sharp on Amazon Linux.
- S3 event notifications to SQS
How an S3 ObjectCreated event can put a message on SQS. Covers the queue access policy, decoding object keys, and writing processed files to a different bucket.