Skip to content

DynamoDB

Roman edited this page Dec 16, 2023 · 3 revisions

RateLimiterDynamo

Usage

Note, if you want to avoid reaching limits on DynamoDB or paying for extra requests, consider inMemoryBlockOnConsumed option to be set.

const {DynamoDB} = require('@aws-sdk/client-dynamodb')
const {RateLimiterDynamo} = require('rate-limiter-flexible')

async function createDynamoDbRateLimiter() {
  const dynamoClient = new DynamoDB({
    region: 'eu-central-1',
    credentials: {
      accessKeyId: 'fake',
      secretAccessKey: 'fake'
    },
    endpoint: 'https://dynamodb.eu-central-1.amazonaws.com'
  });

  return new Promise((resolve, reject) => {
    const rateLimiter = new RateLimiterDynamo({
        storeClient: dynamoClient,
        dynamoTableOpts: {
          readCapacityUnits: 30, // default is 25
          writeCapacityUnits: 30, // default is 25
        },
        points: 4,
        duration: 1,
      },
      (err) => {
        if (err) {
          reject(err)
        } else {
          resolve(rateLimiter)
        }
      })
  })
}

createDynamoDbRateLimiter()
  .then((rateLimiterDynamo) => {
    rateLimiterDynamo.consume('user-id', 2)
      .then((rateLimiterRes) => {
        console.log(rateLimiterRes)
        // {
        // remainingPoints: 2,
        // msBeforeNext: 987,
        // consumedPoints: 2,
        // isFirstInDuration: true
        // }
      })
      .catch((rateLimiterResOrError) => {

      })
  })
  .catch((err) => {

  })
Clone this wiki locally