Skip to content

ElectroDB: A Practical Guide to Entities, Keys, and Queries

Raw DynamoDB code is mostly string building. KeyConditionExpression, ExpressionAttributeNames, ExpressionAttributeValues, and a pk you assemble by hand in four different files. ElectroDB moves all of that into one place: you describe each item type once, and it builds the keys and requests for you, with types.

I use ElectroDB on single-table DynamoDB in every production app I run, rasika.life included. This is the guide I’d give a new engineer on day one. It covers one entity end to end. When you need several entity types in one query, ElectroDB single-table design picks up from here.

What ElectroDB is (and isn’t)

ElectroDB is a TypeScript library that sits on top of the AWS SDK DocumentClient. You give it an Entity: a model name, the attributes, and the indexes. It gives you typed get, query, create, patch, and delete methods, and it composes the key strings from your attributes.

It is not an ORM in the SQL sense. It doesn’t create tables, doesn’t run migrations, and doesn’t check that your indexes serve your access patterns. You still design the schema. ElectroDB makes sure the code that reads and writes it stays consistent.

Install and connect

pnpm add electrodb @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ulid
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'

export const client = DynamoDBDocumentClient.from(new DynamoDBClient({}), {
  marshallOptions: { removeUndefinedValues: true },
})
export const table = process.env.TABLE_NAME ?? 'AppTable'

ElectroDB doesn’t create the table, so define it in your infrastructure. With SST:

const table = new sst.aws.Dynamo('AppTable', {
  fields: { pk: 'string', sk: 'string', gsi1pk: 'string', gsi1sk: 'string' },
  primaryIndex: { hashKey: 'pk', rangeKey: 'sk' },
  globalIndexes: { GSI1: { hashKey: 'gsi1pk', rangeKey: 'gsi1sk' } },
})

Generic key names (pk, sk, gsi1pk, gsi1sk) are the single-table convention. Every entity type writes to the same physical attributes.

Defining an entity

A task tracker. Tasks belong to an org, and each task has one assignee. Two access patterns:

#Access patternIndex
AP1List an org’s tasks, newest firstTable: pk = ORG#<orgId>
AP2List a user’s tasks by status, then due dateGSI1: gsi1pk = USER#<assigneeId>
import { Entity } from 'electrodb'
import { ulid } from 'ulid'
import { client, table } from './client'

export const TaskEntity = new Entity(
  {
    model: { entity: 'task', version: '1', service: 'app' },
    attributes: {
      orgId: { type: 'string', required: true },
      taskId: { type: 'string', required: true, readOnly: true, default: () => ulid() },
      title: { type: 'string', required: true },
      status: { type: ['todo', 'doing', 'done'] as const, required: true, default: 'todo' },
      assigneeId: { type: 'string', required: true },
      dueAt: { type: 'string', required: true }, // ISO date, sorts correctly as a string
      createdAt: { type: 'number', readOnly: true, default: () => Date.now() },
      updatedAt: { type: 'number', watch: '*', set: () => Date.now(), default: () => Date.now() },
    },
    indexes: {
      byOrg: {
        pk: { field: 'pk', composite: ['orgId'], template: 'ORG#${orgId}', casing: 'none' },
        sk: { field: 'sk', composite: ['taskId'], template: 'TASK#${taskId}', casing: 'none' },
      },
      byAssignee: {
        index: 'GSI1',
        pk: { field: 'gsi1pk', composite: ['assigneeId'], template: 'USER#${assigneeId}', casing: 'none' },
        sk: {
          field: 'gsi1sk',
          composite: ['status', 'dueAt'],
          template: 'STATUS#${status}#DUE#${dueAt}',
          casing: 'none',
        },
      },
    },
  },
  { client, table },
)

The pieces worth knowing:

  • model names the entity and its version. ElectroDB stores both on every item and uses them to tell entity types apart in a shared table.
  • attributes are validated on write. An enum array like ['todo', 'doing', 'done'] becomes a TypeScript union. default fills a value on create. watch: '*' with set reruns on every write, which makes updatedAt automatic.
  • indexes list the access patterns. The one index without an index property is the table’s primary key. An index with index: 'GSI1' maps to the GSI with that name.
  • composite lists the attributes that make up each key, in order. template controls the string format.
  • casing: 'none' keeps the case you wrote. Without it ElectroDB lowercases every key, templates included, so ORG#${orgId} would be stored as org#org_acme.

What actually lands in the table

TaskEntity.create({ ... }).params() returns the request without sending it. This is the item ElectroDB 2.15 builds for a new task:

{
  "orgId": "org_acme",
  "taskId": "01JA4D2SX8K3M5N7P9Q1R3T5V7",
  "title": "Ship billing page",
  "status": "todo",
  "assigneeId": "u_alice",
  "dueAt": "2026-10-20",
  "createdAt": 1791528151753,
  "updatedAt": 1791528151754,
  "pk": "ORG#org_acme",
  "sk": "TASK#01JA4D2SX8K3M5N7P9Q1R3T5V7",
  "gsi1pk": "USER#u_alice",
  "gsi1sk": "STATUS#todo#DUE#2026-10-20",
  "__edb_e__": "task",
  "__edb_v__": "1"
}

The request also carries ConditionExpression: attribute_not_exists(pk) AND attribute_not_exists(sk), because this was a create.

Two things to notice. Your attributes are stored as plain fields next to the keys, so the keys are derived data. And __edb_e__ and __edb_v__ are the entity identifiers. ElectroDB filters on them when it reads, so a task query never returns another entity type’s items from the same partition.

I call .params() on any new entity before I deploy it. It’s the fastest way to see whether the keys match the schema you drew.

Writes: create, put, patch, update

Four methods, and the difference is the existence check.

MethodDynamoDB callIf the item existsIf it doesn’t
createPutItem + attribute_not_existsFailsWrites it
putPutItemOverwrites itWrites it
patchUpdateItem + attribute_existsUpdates itFails
updateUpdateItemUpdates itCreates a partial item

My default is create for new items and patch for changes. update with a typo in the ID quietly writes a half-item with just the fields you set. You find it months later.

const { data: task } = await TaskEntity.create({
  orgId: 'org_acme',
  title: 'Ship billing page',
  assigneeId: 'u_alice',
  dueAt: '2026-10-20',
}).go()

await TaskEntity.patch({ orgId: 'org_acme', taskId: task.taskId })
  .set({ title: 'Ship billing page v2' })
  .go()

await TaskEntity.delete({ orgId: 'org_acme', taskId: task.taskId }).go()

There is one surprise here. Change status, and the patch throws:

// Throws: Incomplete composite attributes: Without the composite attributes "dueAt"
// the following access patterns cannot be updated: "byAssignee"
await TaskEntity.patch({ orgId, taskId }).set({ status: 'done' }).go()

status is part of gsi1sk. To rewrite that key, ElectroDB needs every composite in it, and dueAt isn’t in the request. Pass the missing values with .composite():

await TaskEntity.patch({ orgId, taskId })
  .set({ status: 'done' })
  .composite({ assigneeId: task.assigneeId, dueAt: task.dueAt })
  .go()

ElectroDB also adds a condition that those values match what’s stored, so a stale dueAt fails the write instead of corrupting the key. This error is the main reason to keep GSI sort keys short. Every attribute you put in a key is an attribute every update to that key must know.

Reads: get, query, and sort key conditions

// One item by primary key
const { data } = await TaskEntity.get({ orgId: 'org_acme', taskId }).go()

// AP1: an org's tasks, newest first (ULIDs sort by time)
const { data: tasks } = await TaskEntity.query.byOrg({ orgId: 'org_acme' }).go({ order: 'desc' })

// AP2: Alice's open tasks, earliest due first
const { data: todo } = await TaskEntity.query
  .byAssignee({ assigneeId: 'u_alice', status: 'todo' })
  .go()

// AP2 narrowed: Alice's open tasks due in October
const { data: october } = await TaskEntity.query
  .byAssignee({ assigneeId: 'u_alice', status: 'todo' })
  .between({ dueAt: '2026-10-01' }, { dueAt: '2026-10-31' })
  .go()

ElectroDB turns a partial sort key into begins_with. Passing status: 'todo' without dueAt queries gsi1sk beginning with STATUS#todo#DUE#. Composites work left to right, so you can query by status alone, never by dueAt alone. If that’s a problem, the composite order is wrong. begins_with on composite sort keys has the details.

.between(), .begins(), .gt(), .gte(), .lt(), and .lte() all take sort key composites.

Filters cost the same as reads

const { data } = await TaskEntity.query
  .byOrg({ orgId: 'org_acme' })
  .where(({ title }, { contains }) => contains(title, 'billing'))
  .go()

.where() builds a FilterExpression. DynamoDB applies it after reading, so you pay for every item in the partition, not just the matches. Filters are fine for trimming a small result. They are not a replacement for an index.

Pagination

go() returns { data, cursor }. Pass the cursor back to get the next page. It’s null when there are no more pages.

let cursor: string | null = null
do {
  const page = await TaskEntity.query.byOrg({ orgId: 'org_acme' }).go({ cursor, limit: 50 })
  await handle(page.data)
  cursor = page.cursor
} while (cursor)

For scripts that need everything, go({ pages: 'all' }) loops for you. Don’t use it in a request handler on a partition that can grow. DynamoDB pagination covers cursors in API responses.

Defaults that surprise people

Keys are lowercase unless you say otherwise. Covered above. Pick casing: 'none' or accept lowercase, then be consistent across every entity in the table.

A missing composite can still write a key. If an optional attribute is in a GSI key and the template has a prefix before it, ElectroDB 2.15 writes the prefix alone, like USER#. That breaks sparse indexes. DynamoDB GSIs shows the fix.

Changing a template is a data migration. Existing items keep the old keys, and queries built from the new template won’t find them. Bump model.version and backfill.

Your infrastructure and your entities can drift. Rename a GSI in SST and forget the entity, and you get a runtime error on the first query, not a type error.

Where to go next

One entity per query covers most code. For the rest, these posts go deeper:


ElectroDB makes a single-table schema safe to write against. It doesn’t tell you whether the schema is right. I’m building singletable.dev to design the keys visually and export the ElectroDB entities from the diagram.

Tejovanth N

Tejovanth builds on DynamoDB in production: rasika.life, rekha.app, rrmstays. All single-table with ElectroDB.

LinkedIn codeculturecob.com

FAQ

What is ElectroDB?

ElectroDB is a TypeScript library for DynamoDB. You describe each item type once as an Entity, with its attributes and indexes. ElectroDB then builds the keys, the expressions, and the request parameters, and gives you typed methods for reads and writes. It sits on top of the AWS SDK DocumentClient.

Does ElectroDB create DynamoDB tables?

No. ElectroDB is a data access layer. You create the table and its GSIs in your infrastructure code (SST, CDK, Terraform), and the index and field names in your entities must match what you deployed.

What is the difference between create, put, patch, and update in ElectroDB?

create is a put that fails if the item already exists. put writes the whole item and overwrites anything there. patch is an update that fails if the item does not exist. update has no existence check, so updating a key that does not exist creates a partial item. Use create for new items and patch for changes.

Why are my ElectroDB keys lowercase?

ElectroDB lowercases index keys by default, including keys built from a template. Set casing: 'none' on the pk and sk definitions to keep the case you wrote.

Does ElectroDB work with AWS SDK v3?

Yes. Pass a DynamoDBDocumentClient from @aws-sdk/lib-dynamodb as the client. The examples here use ElectroDB 2.15 with SDK v3.

Related

Schema review

Want a second pair of eyes before you ship?

Async DynamoDB schema review. PK/SK design, GSI strategy, ElectroDB entity code. Fixed price, 5 business days.