---
id: I0048
title: "DynamoDB filtered account index"
url: https://carbium.sh/library/integrate/dynamodb-filtered-account-index
collection: Integrations
category: Document and key-value stores
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# DynamoDB filtered account index

A Node script finds a USDC token owner, runs one filtered token-account read, refreshes up to 100 pubkeys with getMultipleAccounts, and prints DynamoDB PutItem requests that carry the context slot and a conditional write.

## Why the index lives on your side

An RPC call answers the question in front of it, at the slot the node is on when the call lands. `getTokenAccountsByOwner` with a mint filter returns every match right now, and the next call runs the filter again. Nothing in that exchange leaves a standing list on the node for you to read back later.

A screen that needs every USDC account of one wallet every few seconds either repeats the filtered read or keeps its own copy. DynamoDB is a good home for the copy. One Query on a partition key returns the whole set, and a conditional write lets a late answer lose to a newer one. The filter you care about becomes the partition key, the account pubkey becomes the sort key, and you own the refresh.

## Table design

One table holds many filters. Each item is one account that matched one filter.

| Attribute | Type | Role |
|---|---|---|
| `filter` | S | Partition key, such as `usdc#<owner>`. One Query on it returns the set. `filter` is a DynamoDB reserved word, so the Query's KeyConditionExpression aliases it (`#f = :f` with `"#f": "filter"`), the same way the write aliases `slot`. |
| `pubkey` | S | Sort key, the account address. |
| `slot` | N | Context slot of the read that produced the item. |
| `lamports` | N | Lamports at that slot. |
| `data` | S | Base64 account data at that slot. |

Every write carries the condition `attribute_not_exists(#s) OR #s < :s`, with `#s` standing for `slot`. A refresh that finishes late carries an older slot, DynamoDB refuses it with `ConditionalCheckFailedException`, and the newer item stays. Catch that exception and move on; it means a newer read already landed.

Name the filter so it holds everything the query depends on. A wallet can own more than one token account for one mint, so `usdc#<owner>` holds several rows, and a second mint gets its own partition value.

## Seeding with one filtered read

The seed is the one call where the node does the filtering for you: `getTokenAccountsByOwner` with the owner and a `mint` filter. It returns each matching token account with its pubkey in a single response. Those pubkeys are the membership list, so the partition is as complete as this read.

Calls through `@solana/kit` 8.6.0 that leave commitment out run at `confirmed`, and the script leaves it out, so the seed reads at confirmed. The script keeps only the pubkeys from the seed. The bytes it stores come from the grouped read in the next step.

The script drops the seed's own slot. Items take their slot from the grouped read, so every item in a group shares one slot and one snapshot.

## Refreshing known keys in groups of 100

After the seed you hold the pubkeys, so a refresh reads them by address with `getMultipleAccounts` and skips the filter. Each answer carries one context slot for the whole group. A group of 100 pubkeys costs 1000 cells, or 1001 over a 4 KiB body. The method takes up to 300 pubkeys, but that is Pro's limit: below Pro the 1024-cell burst caps a call at 100, so code meant for any plan sends 100 at most.

`getMultipleAccounts` runs at [0.5, 15, 50 and 400 calls a second](https://carbium.sh/docs#limits) on Free, Dev, Business and Pro. A partition of 250 accounts is three calls. Send them one after another, because a 1000-cell call nearly empties the 1,024-cell burst, and limits are per account, so every key on it shares one budget.

A null entry in the answer means the account is gone. Delete that item or mark it closed. [Closed account detection](https://carbium.sh/library/howsolana/closed-account-detection) is the entry for that case.

SetAuthority can move a token account to a new owner, and `getMultipleAccounts` still returns it. A refresh that you keep running should compare the mint (bytes 0 to 32) and the owner (bytes 32 to 64) in each account's data with the filter's values, and drop the rows that no longer match.

## The script

`main.ts` finds its own input. It takes the newest USDC mint signature from `getSignaturesForAddress`, which costs 50 cells and reads an address index that keeps up to 30 days. It reads that transaction with `getTransaction` at `maxSupportedTransactionVersion: 1`, also 50 cells, and takes the first owner it finds in `postTokenBalances` for the mint. Then it runs the seed and one group refresh, and prints one PutItem request per account followed by a count line.

Install with `npm install @solana/kit@8.6.0`, set `"type": "module"` in `package.json`, and export `CARBIUM_KEY` with your [API key](https://carbium.sh/docs#auth). `CARBIUM_RPC_URL` is optional. The script writes nothing to AWS. Hand each printed object to `PutItem` through the AWS SDK you already use.

`main.ts` (run: `node main.ts`)

```ts
// I0048 · DynamoDB filtered account index
// https://carbium.sh/library/integrate/dynamodb-filtered-account-index
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY: node main.ts");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const MINT = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); // USDC
const TABLE = "account-index";

// The owner comes from the newest USDC transactions, so the run needs no argument.
async function findOwner() {
  const sigs = await rpc.getSignaturesForAddress(MINT, { limit: 5 }).send();
  for (const s of sigs) {
    if (s.err) continue;
    try {
      const tx = await rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "json" }).send();
      const hit = tx?.meta?.postTokenBalances?.find((b) => b.mint === MINT && b.owner);
      if (hit?.owner) return hit.owner;
    } catch (e) {
      console.error("getTransaction", s.signature, e instanceof Error ? e.message : e);
    }
  }
}

async function main() {
  const owner = await findOwner();
  if (!owner) {
    console.error("No USDC token owner found in the newest signatures; run again.");
    process.exit(1);
  }
  // Seed: one filtered read gives the membership list.
  const seed = await rpc.getTokenAccountsByOwner(owner, { mint: MINT }, { encoding: "base64" }).send();
  const keys = seed.value.map((a) => a.pubkey).slice(0, 100); // at most 100 pubkeys a call below Pro
  if (keys.length === 0) {
    console.error("The owner holds no USDC token account at this slot.");
    return;
  }
  // Refresh: one grouped read, one context slot for every key in it.
  const { context, value } = await rpc.getMultipleAccounts(keys, { encoding: "base64" }).send();
  const filter = `usdc#${owner}`;
  const slot = String(context.slot);
  const items = keys.flatMap((pubkey, i) => {
    const a = value[i];
    if (!a) return []; // closed since the seed
    return [
      {
        TableName: TABLE,
        Item: { filter: { S: filter }, pubkey: { S: pubkey }, slot: { N: slot }, lamports: { N: String(a.lamports) }, data: { S: a.data[0] } },
        ConditionExpression: "attribute_not_exists(#s) OR #s < :s", // an older read never replaces a newer one
        ExpressionAttributeNames: { "#s": "slot" },
        ExpressionAttributeValues: { ":s": { N: slot } },
      },
    ];
  });
  items.forEach((it) => console.log(JSON.stringify(it)));
  console.log(`items ${items.length} slot ${slot}`);
}

main().catch((e) => {
  console.error("failed:", e instanceof Error ? e.message : e);
  process.exit(1);
});
```

The last line reads `items N slot S`, where N is the number of accounts in the group and S is the context slot of the group read. A wallet with one USDC account prints 1.

## Where it ends

- The index is as fresh as your last refresh. Nothing pushes a change into the table. Run the group reads on a timer, or follow [logs](https://carbium.sh/docs#websocket) that mention each indexed token-account pubkey and read on a hit, as [Redis live balance cache](https://carbium.sh/library/integrate/redis-live-balance-cache) does for SOL. A transfer into an existing token account lists that account and never the receiving wallet, so the wallet's own logs miss incoming USDC.
- Membership changes only when you seed again. A token account opened after the seed is missing until the filtered read runs once more, so give the seed its own slower schedule.
- The script covers one filter and one group of 100. A larger partition loops over slices of 100. A filter with thousands of matches makes the seed response large, since the call returns the full set in one answer.
- The owner search walks five signatures and skips errors and nulls. `getTransaction` can answer null for an older signature the index lists, and a run that finds no owner exits with a message.
- The reads run at `confirmed`. If the index feeds settlement, pass `commitment: "finalized"`. The slot attribute orders your writes and nothing more.
- One read of `getMultipleAccounts` is a snapshot. Accounts in one group are read at the same slot, and accounts in different groups can come from different slots.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `getTransaction` fails with -32015. | The transaction is version 1 and the config left out the version. Pass `maxSupportedTransactionVersion: 1` with an encoding, as the script does. The error is uncharged. |
| The log prints `getTransaction <signature>` errors, or a listed signature reads as null. | The signature index reaches below the validator's ledger floor, so an older signature can be listed and still have no transaction to return. The script tries the next of five signatures. If every one fails, run it again to start from newer ones. |
| The group read fails with 429 during a loop over many groups. | Each 100-pubkey call is 1000 cells. Below Pro a class absorbs bursts of 1,024 cells, and on Pro one second of its rate, which is larger, so back-to-back calls wait on the refill. Send groups one after another, wait for the retry-after hint, and remember that every key on the account shares one budget. |
| Every `PutItem` fails with `ConditionalCheckFailedException`. | A stored item already has an equal or newer slot. That is the condition working. Catch the exception and skip the write; a reseed of old data over newer items lands nothing. |
| The script prints `No USDC token owner found in the newest signatures`. | All five newest signatures failed, returned null or listed no owner for the mint. Run it again, which starts from newer signatures. |
| The run ends with 401 on the first call. | The key is unknown at the door. Check that `CARBIUM_KEY` holds the whole key. |

## Questions

### Can the node keep this index for me?

A call answers once, at the slot it reads, and the node keeps no per-query list for you. The seed runs the filter on demand and the table you own keeps the result.

### Why does the table store a slot on every item?

Two refreshes can finish in either order. The slot lets a conditional write refuse an older read, so the item always holds the newest one that reached DynamoDB.

### Can I send 300 pubkeys in one call?

The method takes up to 300, which is Pro's limit. Below Pro the burst caps a call at 100, and a 100-pubkey call costs 1000 cells.

### Why make the filter the partition key?

One Query on that value returns every account that matched. A second filter, such as another owner or mint, is a second partition value in the same table.

## Related

- [SOL balances for many accounts](https://carbium.sh/library/howsolana/sol-balances-for-many-accounts) (How to use Solana, HS0016)
- [Redis live balance cache](https://carbium.sh/library/integrate/redis-live-balance-cache) (Integrations, I0027)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
