0

I have setup Dynamodb table and using it for caching purposes, I have dax client setup as well and writing and reading using node.js's amazon-dax-client. DAX client is not obeying the ttl set on the item.

Here is the configuration of the table, enter image description here

You can see, caching enabled and CacheTTL is set as the ttl attirbute.

Here's the code to write and read items to the cache table.

class DynamodbCache {
  constructor () {
    this.dax = new AmazonDaxClient({
      endpoints: process.env.DAX_CLIENT,
      region,
    })

    this.daxClient = new AWS.DynamoDB.DocumentClient({ service: this.dax })
    this.tableName = process.env.DAX_TABLENAME
  }

  async set(key, value, options = {}) {
    const epochSeconds = this.calculateTTL(options)
    const params = {
      TableName: this.tableName,
      Item: {
        CacheKey: key,
        CacheValue: value,
        CacheTTL: epochSeconds,
      },
    }
    await this.daxClient.put(params).promise()
  }

  async get(key) {
    const params = {
      Key: {
        CacheKey: key,
      },
      TableName: this.tableName,
    }

    const response = await this.daxClient.get(params).promise()
    const { Item = {} } = response
    return Item.CacheValue
  }

  calculateTTL(options = {}) {
    const { ttl = 300 } = options
    if (ttl <= 0) {
      return undefined
    }
    const epochSeconds = Math.floor(Date.now() / 1000) + ttl
    return epochSeconds
  }
}

The following snapshot shows that the cache is being hit even after the max-age is expired. enter image description here

4

0 回答 0