Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(ai-research): write ML key month index entries in batches (#102314)

Robbie53e86ac2bf28
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
index 8fe35fedce70..637283fc6643 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/dynamodb.ts
@@ -1,6 +1,7 @@
import {
AttributeValue,
BatchGetItemCommand,
+ BatchWriteItemCommand,
ConditionalCheckFailedException,
DynamoDBClient,
PutItemCommand,
@@ -230,6 +231,53 @@ export class MlKeyDynamoDB {
return (await this.read([key], deadline)).get(tableKeyString(key)) ?? {}
}
+ /** Writes rows that need no condition, 25 to a request, so a key costs one write request rather than two. */
+ public async putMany(rows: Array<{ key: TableKey; attributes: DynamoItem }>, deadline: AbortSignal): Promise<void> {
+ const chunks: (typeof rows)[] = []
+ for (let offset = 0; offset < rows.length; offset += 25) {
+ chunks.push(rows.slice(offset, offset + 25))
+ }
+ await Promise.all(
+ chunks.map((chunk) =>
+ this.writeConcurrency(async () => {
+ let pending = chunk.map(({ key, attributes }) => ({
+ PutRequest: { Item: { ...encodeKey(key), ...attributes } },
+ }))
+ for (let attempt = 0; pending.length && attempt < this.attempts; attempt++) {
+ let response
+ try {
+ response = await this.timed('dynamodb_put_batch', () =>
+ this.client.send(
+ new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } }),
+ { abortSignal: this.requestSignal(deadline) }
+ )
+ )
+ } catch (error) {
+ if (!isTransientError(error) || deadline.aborted || attempt === this.attempts - 1) {
+ throw error
+ }
+ await this.backoff(attempt, deadline)
+ if (deadline.aborted) {
+ throw error
+ }
+ continue
+ }
+ pending = (response.UnprocessedItems?.[this.tableName] ?? []) as typeof pending
+ if (pending.length) {
+ await this.backoff(attempt, deadline)
+ if (deadline.aborted) {
+ throw new DOMException('ML key manager index write deadline expired', 'AbortError')
+ }
+ }
+ }
+ if (pending.length) {
+ throw new Error('ML key manager index write exhausted retries')
+ }
+ })
+ )
+ )
+ }
+
public async put(key: TableKey, attributes: DynamoItem, deadline?: AbortSignal): Promise<void> {
await this.writeConcurrency(() =>
this.timed('dynamodb_put', () =>
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
index c621e7dac80b..f091ae6474df 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
@@ -1,5 +1,6 @@
import {
BatchGetItemCommand,
+ BatchWriteItemCommand,
ConditionalCheckFailedException,
DynamoDBClient,
PutItemCommand,
@@ -48,9 +49,30 @@ class DynamoBoundary {
public readonly items = new Map<string, DynamoItem>()
public readSizes: number[] = []
public writes = 0
+ public writeRequests = 0
+ public deferWrites = 0
+ public writeBatchSizes: number[] = []
public conditionalFailures = 0
- public async send(command: BatchGetItemCommand | PutItemCommand): Promise<object> {
+ public async send(command: BatchGetItemCommand | BatchWriteItemCommand | PutItemCommand): Promise<object> {
+ if (command instanceof BatchWriteItemCommand) {
+ const requests = command.input.RequestItems![table]
+ if (requests.length > 25) {
+ throw new Error(`BatchWriteItem takes at most 25 rows, got ${requests.length}`)
+ }
+ this.writeBatchSizes.push(requests.length)
+ this.writeRequests += 1
+ await Promise.resolve()
+ // DynamoDB answers a partial throttle by storing some rows and returning the rest as unprocessed.
+ const deferred = Math.min(this.deferWrites, requests.length)
+ this.deferWrites -= deferred
+ for (const request of requests.slice(deferred)) {
+ const row = request.PutRequest!.Item!
+ this.writes += 1
+ this.items.set(JSON.stringify([row.pk.S, row.sk.S]), row)
+ }
+ return deferred ? { UnprocessedItems: { [table]: requests.slice(0, deferred) } } : {}
+ }
if (command instanceof BatchGetItemCommand) {
const keys = command.input.RequestItems![table].Keys!
if (keys.some((key) => Buffer.byteLength(key.sk.S!) > 1024)) {
@@ -69,6 +91,7 @@ class DynamoBoundary {
const item = command.input.Item!
const id = JSON.stringify([item.pk.S, item.sk.S])
this.writes += 1
+ this.writeRequests += 1
await Promise.resolve()
if (command.input.ConditionExpression === 'attribute_not_exists(pk)' && this.items.has(id)) {
this.conditionalFailures += 1
@@ -141,6 +164,46 @@ describe('ML session key batches', () => {
expect((await reader.read([sessionKeyId(session.teamId, session.sessionId)])).size).toBe(1)
})
+ it.each([
+ ['retries only the rows a batch write left unprocessed', 1, true],
+ ['gives up when a batch write keeps leaving rows unprocessed', 500, false],
+ ])('%s', async (_label, deferred, succeeds) => {
+ boundary.deferWrites = deferred
+ const batch = await store.prepare([session])
+ jest.useFakeTimers()
+ const settled = batch.commit().then(
+ () => 'committed',
+ () => 'failed'
+ )
+ await jest.runAllTimersAsync()
+ expect(await settled).toBe(succeeds ? 'committed' : 'failed')
+ if (succeeds) {
+ const location = sessionKeyId(session.teamId, session.sessionId)
+ expect(boundary.items.has(tableKeyString(monthKeyIndexId({ ...session }, location)))).toBe(true)
+ // Two index rows and two keys. A retry that re-sent the whole batch would store an index row twice.
+ expect(boundary.writes).toBe(4)
+ // One batch write, one retry carrying the single deferred row, and a put for each key.
+ expect(boundary.writeRequests).toBe(4)
+ }
+ })
+
+ it('writes one request per key instead of two by batching the month index entries', async () => {
+ const identities = Array.from({ length: 60 }, (_, index) => ({
+ ...session,
+ sessionId: `01994569-4380-7000-8000-${(index + 200).toString(16).padStart(12, '0')}`,
+ }))
+ const batch = await store.prepare(identities)
+ jest.useFakeTimers()
+ const committing = batch.commit()
+ await jest.runAllTimersAsync()
+ await committing
+ // 60 session keys and one team image key. Each is one conditional put, and their 61 index entries pack into
+ // three batches of at most 25, so 122 requests become 64.
+ expect(boundary.writes).toBe(122)
+ expect(boundary.writeRequests).toBe(64)
+ expect([...boundary.writeBatchSizes].sort((a, b) => b - a)).toEqual([25, 25, 11])
+ })
+
it('commits concurrent new sessions without conditional failures', async () => {
await (await store.prepare([session])).commit()
const identities = Array.from({ length: 120 }, (_, index) => ({
@@ -264,7 +327,7 @@ describe('ML session key batches', () => {
const send = boundary.send.bind(boundary)
let remaining = 1
jest.spyOn(boundary, 'send').mockImplementation((command) => {
- if (command instanceof PutItemCommand && command.input.Item!.pk.S!.startsWith('month:') && remaining > 0) {
+ if (command instanceof BatchWriteItemCommand && remaining > 0) {
remaining -= 1
return Promise.reject(transientError('ProvisionedThroughputExceededException'))
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
index 7d4a0059e2e3..39b1828aeae3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
@@ -159,17 +159,22 @@ export class MlKeyBatch {
// The index entry goes first and is idempotent, so every stored key has an index entry even when the key put fails or a retried put reports the batch's own write as a competitor's. An index entry without a key is harmless: the month sweep leaves a tombstone that a later key put respects.
private async persist(deadline: AbortSignal): Promise<void> {
let dropped = 0
- const results = await Promise.allSettled(
- [...this.keys].map(async ([id, key]) => {
- if (this.state.has(id)) {
- return
+ const unstored = [...this.keys].filter(([id]) => !this.state.has(id))
+ // Every index entry goes in before any key, so a key put that fails still leaves its entry, as it did when each
+ // key wrote its own. These need no condition, so they batch and a key costs one write request rather than two.
+ await this.db.putMany(
+ unstored.map(([, key]) => {
+ const location = storedKeyId(key.identity)
+ return {
+ key: monthKeyIndexId(key.identity, location),
+ attributes: { key_pk: { S: location.pk }, key_sk: { S: location.sk } },
}
+ }),
+ deadline
+ )
+ const results = await Promise.allSettled(
+ unstored.map(async ([id, key]) => {
const location = storedKeyId(key.identity)
- await this.db.put(
- monthKeyIndexId(key.identity, location),
- { key_pk: { S: location.pk }, key_sk: { S: location.sk } },
- deadline
- )
const stored = await this.db.putIfAbsent(
location,
{
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 803dd0422536..a24238469b84 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -26,6 +26,7 @@ export type MlKeyRequest =
| 'kms_wait'
| 'dynamodb_read'
| 'dynamodb_put'
+ | 'dynamodb_put_batch'
| 'dynamodb_put_if_absent'
export type MlImageSourceKind = 'inline' | 'url'
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index b650f2c99f6d..7322c88b6095 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -56,7 +56,7 @@ Ingestion processes key state in batches:
A conditional put refuses to recreate a shredded session key.
A team blocked during a batch is refused by every reader at once and by the next batch, which reads the block row live, and the deletion worker sweeps the team once more after the reader lease, so a key stored after the block is shredded.
Kafka offsets advance only after the required writes and publication succeed.
-Bulk reads use batches of at most 100 keys; each new key is one conditional put, so no commit in the fleet waits on another.
+Bulk reads use batches of at most 100 keys. Each new key is one conditional put, so no commit in the fleet waits on another, and the month index entries it needs go in together, at most 25 to a request.
Reads use strongly consistent `BatchGetItem` requests with bounded retries for unprocessed keys and for a throttled request.
A retry stops when the caller's deadline expires.