Skip to content

Commit bf27141

Browse files
pudkrongcoderbyheart
authored andcommitted
fix: distributed lock ttl
DynamoDB ttl does not delete the expired item immediately. Therefore, comparing ttl with current time is more accurate
1 parent 17bb900 commit bf27141

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

lambda/fetchDeviceShadow.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ const db = new DynamoDBClient({})
4747
const log = logger('fetchDeviceShadow')
4848

4949
const lockName = 'fetch-shadow'
50-
const lockTTL = 30
50+
const lockTTLSeconds = 5
5151
const lock = createLock(db, lockTableName)
5252

5353
const eventBus = new EventBridgeClient({})
@@ -72,7 +72,7 @@ const deviceShadowPromise = (async () => {
7272

7373
const h = async (): Promise<void> => {
7474
const deviceShadow = await deviceShadowPromise
75-
const lockAcquired = await lock.acquiredLock(lockName, lockTTL)
75+
const lockAcquired = await lock.acquiredLock(lockName, lockTTLSeconds)
7676
if (lockAcquired === false) {
7777
log.info(`Other process is still running, then ignore`)
7878
return

websocket/lock.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ export const createLock: (
99
db: DynamoDBClient,
1010
tableName: string,
1111
) => {
12-
acquiredLock: (name: string, ttl: number) => Promise<boolean>
12+
acquiredLock: (name: string, ttlSeconds: number) => Promise<boolean>
1313
releaseLock: (name: string) => Promise<void>
1414
} = (db: DynamoDBClient, tableName: string) => {
15-
const acquiredLock = async (name: string, ttl: number) => {
16-
const currentTime = Date.now()
17-
const timeToLive = currentTime + ttl
15+
const acquiredLock = async (name: string, ttlSeconds: number) => {
16+
const currentTime = Math.floor(Date.now() / 1000)
17+
const timeToLive = currentTime + ttlSeconds
1818

1919
try {
2020
await db.send(
@@ -25,7 +25,15 @@ export const createLock: (
2525
ownerId: { S: process.pid.toString() },
2626
ttl: { N: timeToLive.toString() },
2727
},
28-
ConditionExpression: 'attribute_not_exists(lockName)',
28+
ExpressionAttributeNames: {
29+
'#ttlName': 'ttl',
30+
'#lockName': 'lockName',
31+
},
32+
ExpressionAttributeValues: {
33+
':currentTime': { N: currentTime.toString() },
34+
},
35+
ConditionExpression:
36+
'attribute_not_exists(#lockName) OR #ttlName < :currentTime',
2937
}),
3038
)
3139

0 commit comments

Comments
 (0)