DynamoDB in Spring Boot applications

DynamoDB answers any request in single-digit milliseconds at any scale, but only for the questions its keys were designed to answer. Coming from SQL, the hard part is not the Java API, it is the key design. This page explains how DynamoDB stores and finds items, works through key design and capacity with runnable models, and shows the Spring Cloud AWS 4 code for entities, queries and locking.

Share

Contents

How DynamoDB stores and finds items

DynamoDB is a key-value and document database run by AWS. A table holds items, each a set of attributes up to 400 KB in total, and there is no fixed schema apart from the key. The key is what everything else depends on:

  • Partition key: DynamoDB hashes it to decide which storage partition holds the item. All reads and writes of one item go to one partition, which is why they stay fast however large the table grows.
  • Sort key (optional): items with the same partition key form an item collection, stored together and sorted by the sort key. A Query can read a range of that collection in one request.

Those two facts define what is cheap and what is not:

DynamoDB read operations
OperationNeedsCostUse for
GetItemThe full keyOne itemLoading one entity by ID
QueryOne partition key, optional sort-key conditionOnly the items readEvery planned access pattern
Query on a GSIThe index's keysItems read from the indexAccess patterns by another attribute
ScanNothingEvery item in the tableExports and one-off jobs, never request paths

There are no joins, and a filter expression is applied after the items are read, so it saves network traffic but not cost. The design process is therefore the reverse of SQL: list the application's access patterns first, then choose keys so that each pattern is a GetItem or a Query. A table is billed either on demand, per request, or in provisioned read and write capacity units.

From Spring Boot, DynamoDB is used through Spring Cloud AWS, whose DynamoDbTemplate wraps the AWS SDK 2 enhanced client. Neither the SDK's DynamoDB module nor a DynamoDB endpoint is available where this page was built, so the Spring and SDK examples are marked as not run; they were checked against the Spring Cloud AWS 4 reference documentation, its source code and the AWS documentation. The two programs that are shown running are plain-Java models of key design and capacity, not DynamoDB itself.

Designing keys for access patterns

An online shop needs four reads for a customer page: the profile, all orders, the orders of one month, and the latest order. Putting the customer in the partition key and a typed, sortable value in the sort key serves all four from one item collection. This program models such a collection with a sorted map, which is how DynamoDB keeps the items of one partition:

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

// A plain-Java model of how DynamoDB stores a partition: items with the same partition
// key kept sorted by sort key. It is NOT DynamoDB; it shows what Query can and cannot do.
public class ItemCollectionModel {

    private final Map<String, NavigableMap<String, String>> partitions = new TreeMap<>();

    void put(String pk, String sk, String data) {
        partitions.computeIfAbsent(pk, k -> new TreeMap<>()).put(sk, data);
    }

    // Query: exactly one partition key, then a condition on the sort key
    List<String> query(String pk, String from, String to, boolean forward, int limit) {
        NavigableMap<String, String> range = partitions.getOrDefault(pk, new TreeMap<>())
                .subMap(from, true, to, true);
        List<String> page = new ArrayList<>();
        String last = null;
        for (var e : (forward ? range : range.descendingMap()).entrySet()) {
            if (page.size() == limit) {
                // like DynamoDB: the key of the last item returned, to resume after it
                page.add("(more items: LastEvaluatedKey = " + last + ")");
                break;
            }
            page.add(e.getKey() + " -> " + e.getValue());
            last = e.getKey();
        }
        return page;
    }

    static List<String> beginsWith(ItemCollectionModel t, String pk, String prefix) {
        return t.query(pk, prefix, prefix + Character.MAX_VALUE, true, Integer.MAX_VALUE);
    }

    public static void main(String[] args) {
        ItemCollectionModel table = new ItemCollectionModel();
        table.put("CUSTOMER#ana", "PROFILE", "{name: Ana, tier: gold}");
        table.put("CUSTOMER#ana", "ORDER#2026-10-15#A-0", "{total: 18.00}");
        table.put("CUSTOMER#ana", "ORDER#2026-11-01#A-1", "{total: 42.50}");
        table.put("CUSTOMER#ana", "ORDER#2026-11-09#A-2", "{total: 7.25}");
        table.put("CUSTOMER#ana", "ADDRESS#home", "{city: Porto}");
        table.put("CUSTOMER#ben", "PROFILE", "{name: Ben, tier: basic}");

        System.out.println("Everything for one customer, in sort-key order:");
        table.query("CUSTOMER#ana", "", "~", true, 10).forEach(s -> System.out.println("  " + s));

        System.out.println("begins_with(SK, \"ORDER#\"):");
        beginsWith(table, "CUSTOMER#ana", "ORDER#").forEach(s -> System.out.println("  " + s));

        System.out.println("SK BETWEEN ORDER#2026-11-01 AND ORDER#2026-11-30:");
        table.query("CUSTOMER#ana", "ORDER#2026-11-01", "ORDER#2026-11-30", true, 10)
                .forEach(s -> System.out.println("  " + s));

        System.out.println("Latest order (ScanIndexForward = false, Limit = 1):");
        table.query("CUSTOMER#ana", "ORDER#", "ORDER#~", false, 1)
                .forEach(s -> System.out.println("  " + s));

        System.out.println("All gold customers: not a Query on this key design;"
                + " it needs a Scan or a GSI on tier");
    }
}
Output
Everything for one customer, in sort-key order:
  ADDRESS#home -> {city: Porto}
  ORDER#2026-10-15#A-0 -> {total: 18.00}
  ORDER#2026-11-01#A-1 -> {total: 42.50}
  ORDER#2026-11-09#A-2 -> {total: 7.25}
  PROFILE -> {name: Ana, tier: gold}
begins_with(SK, "ORDER#"):
  ORDER#2026-10-15#A-0 -> {total: 18.00}
  ORDER#2026-11-01#A-1 -> {total: 42.50}
  ORDER#2026-11-09#A-2 -> {total: 7.25}
SK BETWEEN ORDER#2026-11-01 AND ORDER#2026-11-30:
  ORDER#2026-11-01#A-1 -> {total: 42.50}
  ORDER#2026-11-09#A-2 -> {total: 7.25}
Latest order (ScanIndexForward = false, Limit = 1):
  ORDER#2026-11-09#A-2 -> {total: 7.25}
  (more items: LastEvaluatedKey = ORDER#2026-11-09#A-2)
All gold customers: not a Query on this key design; it needs a Scan or a GSI on tier
  • All of Ana's items share the partition key CUSTOMER#ana and came back in sort-key order: ADDRESS#home, then the three orders, then PROFILE. One Query for that key would return the whole customer page in a single request.
  • begins_with(SK, "ORDER#") selected only the three orders. The ORDER# prefix makes the item type part of the key, which is how one table can hold several kinds of entity.
  • Because the order date is in the sort key in ISO format, BETWEEN found the two November orders. String order equals date order only with a fixed format such as 2026-11-01.
  • Reading backwards with a limit of 1 gave the latest order, A-2. The LastEvaluatedKey marks where the page ended; passed back as ExclusiveStartKey, it continues the query after that item.
  • "All gold customers" cannot be answered: the tier is not part of any key. It needs a Scan of the whole table, or a global secondary index whose partition key is the tier.

This is the idea behind single-table design: several entity types in one table, with keys built from type prefixes so that related items sit in one item collection. It makes the planned reads very cheap. The price is that unplanned reads are expensive or impossible, and the table is hard to read for someone who does not know the key scheme. Many teams use one table per aggregate instead, with the same key techniques, which is easier to understand and still avoids joins.

Choose a partition key with many distinct values that are used evenly, such as a customer ID. A key with few values, such as a status or a date, sends most traffic to a few partitions, and those partitions are throttled while the rest of the table is idle.

Entities and DynamoDbTemplate (not run)

The Spring Cloud AWS DynamoDB starter auto-configures a DynamoDbClient, a DynamoDbEnhancedClient and a DynamoDbTemplate:

XML
<dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-dynamodb</artifactId>
</dependency>

Its version comes from the spring-cloud-aws-dependencies BOM, as on the SQS page. Entities use the enhanced client's annotations, on the getters of a mutable class:

Java
@DynamoDbBean
public class CustomerItem {
    private String pk;            // CUSTOMER#ana
    private String sk;            // PROFILE, ORDER#2026-11-01#A-1, ...
    private String tier;
    private BigDecimal total;
    private int points;
    private Long version;

    @DynamoDbPartitionKey
    @DynamoDbAttribute("PK")
    public String getPk() { return pk; }
    public void setPk(String pk) { this.pk = pk; }

    @DynamoDbSortKey
    @DynamoDbAttribute("SK")
    public String getSk() { return sk; }
    public void setSk(String sk) { this.sk = sk; }

    @DynamoDbSecondaryPartitionKey(indexNames = "by-tier")
    public String getTier() { return tier; }
    public void setTier(String tier) { this.tier = tier; }

    public BigDecimal getTotal() { return total; }
    public void setTotal(BigDecimal total) { this.total = total; }

    public int getPoints() { return points; }
    public void setPoints(int points) { this.points = points; }

    @DynamoDbVersionAttribute
    public Long getVersion() { return version; }
    public void setVersion(Long version) { this.version = version; }
}
Java
@Service
public class CustomerStore {
    private final DynamoDbTemplate dynamo;

    public CustomerStore(DynamoDbTemplate dynamo) {
        this.dynamo = dynamo;
    }

    public CustomerItem profile(String customerId) {                  // GetItem
        return dynamo.load(Key.builder().partitionValue("CUSTOMER#" + customerId)
                .sortValue("PROFILE").build(), CustomerItem.class);
    }

    public List<CustomerItem> orders(String customerId) {              // Query
        QueryEnhancedRequest request = QueryEnhancedRequest.builder()
                .queryConditional(QueryConditional.sortBeginsWith(Key.builder()
                        .partitionValue("CUSTOMER#" + customerId).sortValue("ORDER#").build()))
                .build();
        return dynamo.query(request, CustomerItem.class).items().stream().toList();
    }

    public Optional<CustomerItem> latestOrder(String customerId) {
        QueryEnhancedRequest request = QueryEnhancedRequest.builder()
                .queryConditional(QueryConditional.sortBeginsWith(Key.builder()
                        .partitionValue("CUSTOMER#" + customerId).sortValue("ORDER#").build()))
                .scanIndexForward(false)
                .limit(1)
                .build();
        return dynamo.query(request, CustomerItem.class).items().stream().findFirst();
    }
}
  • DynamoDbTemplate offers save, update, delete, load, query and scan, each also in a form that takes the enhanced client's request object, and query and scan in a form that takes an index name.
  • query returns a PageIterable. Iterating items() fetches further pages as needed, following LastEvaluatedKey automatically. For an API that pages to its own clients, iterate the pages instead and pass the last key back to the caller.
  • The table name comes from the class name in snake case, customer_item here. spring.cloud.aws.dynamodb.table-prefix and table-suffix add an environment name, such as prod_, and a DynamoDbTableNameResolver bean replaces the rule entirely.
  • With Spring Boot DevTools, the Spring Cloud AWS documentation recommends defining the schema with StaticTableSchema, because the bean-based schema runs into a class loader problem in the AWS SDK on restart.

Concurrent updates and transactions (not run)

DynamoDB has no locks to take. Two requests that read the same item, change it and write it back will silently lose one of the changes, unless the write is conditional. @DynamoDbVersionAttribute turns every save and update into one: the enhanced client writes the item only if its stored version still equals the version that was read, and increases it:

Java
public void addLoyaltyPoints(String customerId, int points) {
    for (int attempt = 1; ; attempt++) {
        CustomerItem profile = profile(customerId);
        profile.setPoints(profile.getPoints() + points);
        try {
            dynamo.update(profile);          // condition: version = the version read
            return;
        } catch (ConditionalCheckFailedException e) {
            if (attempt == 3) {
                throw e;                     // someone else keeps winning: give up
            }
        }
    }
}
  • The losing writer gets ConditionalCheckFailedException and must read again, as the loop does. This is optimistic locking, the same idea as JPA's @Version.
  • For a plain counter, an update expression such as ADD points :n is better still: it changes the value on the server in one request, with no read and no conflict.
  • For changes to several items that must happen together, such as moving stock between two warehouses, TransactWriteItems applies up to 100 actions atomically, each with its own condition. Transactional reads and writes cost twice the capacity of ordinary ones, as the next section shows.

Capacity units and what they cost

In provisioned mode, a table is given read and write capacity units, and requests above them are throttled. On-demand tables are billed in request units that follow the same size rules. The rules from the AWS documentation are short enough to compute: a read of up to 4 KB costs one read capacity unit when strongly consistent and half when eventually consistent, and a write of up to 1 KB costs one write capacity unit, with sizes rounded up. This program applies them to a typical workload:

Java
public class CapacityPlanner {

    // AWS definitions: 1 RCU = one strongly consistent read per second of up to 4 KB,
    // or two eventually consistent reads; 1 WCU = one write per second of up to 1 KB.
    // Transactional reads and writes cost twice as much. Sizes are rounded up.
    static long readUnits(double itemKb, double readsPerSecond, String consistency) {
        long perRead = (long) Math.ceil(itemKb / 4);
        double factor = switch (consistency) {
            case "eventual" -> 0.5;
            case "strong" -> 1;
            case "transactional" -> 2;
            default -> throw new IllegalArgumentException(consistency);
        };
        return (long) Math.ceil(perRead * factor * readsPerSecond);
    }

    static long writeUnits(double itemKb, double writesPerSecond, boolean transactional) {
        long perWrite = (long) Math.ceil(itemKb);
        return (long) Math.ceil(perWrite * writesPerSecond * (transactional ? 2 : 1));
    }

    public static void main(String[] args) {
        System.out.println("Reads of a 3.5 KB item, 200 per second:");
        for (String c : new String[] {"eventual", "strong", "transactional"}) {
            System.out.printf("  %-13s %4d RCU%n", c, readUnits(3.5, 200, c));
        }
        System.out.println("Reads of a 4.5 KB item, 200 per second, eventual: "
                + readUnits(4.5, 200, "eventual") + " RCU");

        System.out.println("Writes of a 1.5 KB item, 50 per second:");
        System.out.println("  standard      " + writeUnits(1.5, 50, false) + " WCU");
        System.out.println("  transactional " + writeUnits(1.5, 50, true) + " WCU");

        // every write that changes an indexed attribute is also written to each GSI
        long table = writeUnits(1.5, 50, false);
        long perIndex = writeUnits(1.5, 50, false);   // index projecting all attributes
        System.out.println("Same writes with 2 GSIs projecting ALL attributes: "
                + table + " + 2 x " + perIndex + " = " + (table + 2 * perIndex) + " WCU");

        System.out.println("Writes of a 0.9 KB item instead: "
                + writeUnits(0.9, 50, false) + " WCU");
    }
}
Output
Reads of a 3.5 KB item, 200 per second:
  eventual       100 RCU
  strong         200 RCU
  transactional  400 RCU
Reads of a 4.5 KB item, 200 per second, eventual: 200 RCU
Writes of a 1.5 KB item, 50 per second:
  standard      100 WCU
  transactional 200 WCU
Same writes with 2 GSIs projecting ALL attributes: 100 + 2 x 100 = 300 WCU
Writes of a 0.9 KB item instead: 50 WCU
  • 200 reads per second of a 3.5 KB item cost 100 RCU eventually consistent, 200 strongly consistent and 400 in transactions. Eventually consistent reads, the default, may miss a write from the last moment; that is acceptable for most pages and halves the cost.
  • An item of 4.5 KB costs twice as much as one of 3.5 KB: 200 RCU instead of 100, because each read now rounds up to two 4 KB units.
  • Writes are counted per 1 KB: 50 writes of 1.5 KB cost 100 WCU, but 50 writes of 0.9 KB only 50.
  • Each global secondary index is written whenever an indexed item changes. With two indexes projecting all attributes, the same 50 writes cost 300 WCU in total, three times the table's own writes.

Two design rules follow. Keep items small and split rarely read data, such as a long description, into a separate item, since every read pays for the whole item. And project only the attributes an index needs, with KEYS_ONLY or INCLUDE, rather than ALL.

Configuration and local development (not run)

The region, an optional table prefix per environment and, for local work, the endpoint are the only settings most applications need:

YAML
spring:
  cloud:
    aws:
      region:
        static: eu-west-1
      dynamodb:
        table-prefix: dev_
        # DynamoDB Local or LocalStack; leave unset in AWS
        endpoint: http://localhost:8000
  • Credentials come from the AWS SDK's default chain, as for every AWS client: environment variables, the shared profile, or the IAM role of the instance, task or pod. Grant only the actions and tables the service needs.
  • Tables, keys and indexes are part of the infrastructure, so create them with CloudFormation, CDK or Terraform, not from application code at start-up.
  • For tests, DynamoDB Local and LocalStack both run in a container. Start one with Testcontainers and set spring.cloud.aws.dynamodb.endpoint with @DynamicPropertySource, as the Testcontainers page shows.
  • With the amazon-dax-client dependency and spring.cloud.aws.dynamodb.dax.url, the starter configures a DynamoDB Accelerator client, an in-memory cache in front of the table for read-heavy workloads.

Traps when coming from SQL

  • Scans on request paths: a scan with a filter reads, and pays for, the whole table on every call. It works with test data and fails in production.
  • Filters mistaken for conditions: a filter expression is applied after the read. A Query that reads 1,000 items and filters them down to 3 costs 1,000 items, and with limit it may return no items at all while more pages exist.
  • Missing pages: one Query returns at most 1 MB. Code that reads only the first page silently loses items once the data grows; iterate the PageIterable.
  • Hot partitions: a partition key such as today's date puts all of today's writes in one partition. Add a suffix, such as a shard number, or choose another key.
  • Read, modify, write without a condition: concurrent updates overwrite each other. Use a version attribute or an update expression.
  • Numbers as floating point: DynamoDB stores numbers as exact decimals. Map money to BigDecimal, not double.

Choosing a DynamoDB approach

DynamoDB techniques for common needs
NeedTechnique
Load one entity by IDload with the full key (GetItem)
Related items read togetherSame partition key, typed sort-key prefixes, one query
Ranges, latest first, time windowsSortable sort key, scanIndexForward(false), limit
Lookups by another attributeA global secondary index with a narrow projection
Concurrent updates of one item@DynamoDbVersionAttribute, or an update expression
Several items changed atomicallyTransactWriteItems
Ad hoc queries, reports, joinsA relational database, or an export to analytics; not DynamoDB

DynamoDB is an excellent fit when the access patterns are known and must stay fast at any scale, and a poor one when the questions change every month. For a relational model with joins and ad hoc queries in Spring, see Spring Data JPA; for events that DynamoDB changes can trigger, see Spring Cloud Function on Lambda.