Skip to main content
InterviewHubPRO
Section Overview
Q28

Question 28 of 50

Part 3: Advanced Architecture, Scale & Internals (Senior / Lead)

56%
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: PutItem with ConditionExpression: attribute_not_exists(lockName) OR lockExpiresAt < :now and set lockExpiresAt to now + leaseSeconds.
  • Heartbeat: Extend lockExpiresAt conditionally 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;
  }
}