Search code examples
amazon-dynamodbaws-amplifyaws-appsync

Auto-increment integer in dynamodb


I'm modeling a dynamodb diagram for an invoice app and I'm looking for generate the unique invoice id that need to be incremented from 1 to X. There is in 2019 a solution about this kind of problem with aws appsync and dynamodb as datasource ?


Solution

  • Auto-incrementing integers are not a recommended pattern in DynamoDB although it is possible to implement something similar using application level logic. A DynamoDB table is distributed to many logical partitions according to the table's partition key. Items are then sorted within that partition according to their sort key. You will need to decide what structure makes sense for you app and what an auto-incrementing means for your app. The simplest case would be to omit a sort key and treat the auto-incremented id as the partition key which would guarantee its uniqueness but also has implications that every row lives in its own partition and thus listing all invoices would have to be a Scan and thus does not preserve order which may or may not make sense for your app.

    As mentioned in this SO post (How to use auto increment for primary key id in dynamodb) you can use code like this:

    const params = {
      TableName: 'CounterTable',
      Key: { HashKey : 'auto-incrementing-counter' },
      UpdateExpression: 'ADD #a :x',
      ExpressionAttributeNames: {'#a' : "counter_value"},
      ExpressionAttributeValues: {':x' : 1},
      ReturnValues: "UPDATED_NEW" // ensures you get value back the new key
    };
    new AWS.DynamoDB.DocumentClient().update(params, function(err, data) {});
    

    to atomically increment the integer stored in the CounterTable row designated by the partition key "auto-incrementing-counter". After the atomic increment, you can use the returned id to create the new Invoice.

    You can implement this pattern using DynamoDB & AppSync but the first thing to decide is if it suits your use case. You may also be interested in the RDS integration via the RDS data API which would have more native support for auto-incrementing IDs but would lose out on the set it and forget it scaling of DynamoDB.