Amazon DynamoDB (50 Qs)•Part 3: Advanced Architecture, Scale & Internals (Senior / Lead)
How do you implement distributed locking in DynamoDB?
senior LevelCode ExampleSystem DesignDynamoDB
In Simple Words: Use conditional writes with TTL:
- Acquire lock:
PutItemwithConditionExpression: attribute_not_exists(lockName) OR lockExpiresAt < :nowand setlockExpiresAttonow + leaseSeconds. - Heartbeat: Extend
lockExpiresAtconditionally matching lease owner ID. - Release lock: Delete item conditionally matching lease owner ID.
Code Example (Distributed Mutex with TTL Lease)
typescript
import { PutCommand } from '@aws-sdk/lib-dynamodb';
export async function acquireLock(docClient: any, lockKey: string, ownerId: string, ttlSeconds = 30) {
const now = Math.floor(Date.now() / 1000);
const leaseExpiresAt = now + ttlSeconds;
try {
await docClient.send(
new PutCommand({
TableName: 'DistributedLocks',
Item: {
LockKey: lockKey,
OwnerId: ownerId,
ExpiresAt: leaseExpiresAt,
},
// Only acquire if no lock exists OR current lock lease has expired
ConditionExpression: 'attribute_not_exists(LockKey) OR ExpiresAt < :now',
ExpressionAttributeValues: { ':now': now },
})
);
return true; // Lock acquired successfully
} catch (err: any) {
if (err.name === 'ConditionalCheckFailedException') return false; // Lock occupied
throw err;
}
}
Code Example (Distributed Mutex with TTL Lease)
typescript
import { PutCommand } from '@aws-sdk/lib-dynamodb';
export async function acquireLock(docClient: any, lockKey: string, ownerId: string, ttlSeconds = 30) {
const now = Math.floor(Date.now() / 1000);
const leaseExpiresAt = now + ttlSeconds;
try {
await docClient.send(
new PutCommand({
TableName: 'DistributedLocks',
Item: {
LockKey: lockKey,
OwnerId: ownerId,
ExpiresAt: leaseExpiresAt,
},
// Only acquire if no lock exists OR current lock lease has expired
ConditionExpression: 'attribute_not_exists(LockKey) OR ExpiresAt < :now',
ExpressionAttributeValues: { ':now': now },
})
);
return true; // Lock acquired successfully
} catch (err: any) {
if (err.name === 'ConditionalCheckFailedException') return false; // Lock occupied
throw err;
}
}