Chris Tam · Last updated 13 November 2026
Product analytics can measure activation when an application commits a meaningful outcome. I'll build a local command-line workspace: one command creates the workspace and another saves a record. The first saved record creates its activation event in the same database transaction. This is a real local state change; the example doesn't host a collaboration service.
What you'll build
A Node.js fixture that stores workspaces and records in SQLite, commits one activation outbox row per synthetic user, and sends pending rows through the Amplitude SDK. A failed upload stays pending; a retry keeps its original timestamp, device ID and insert ID.
Prerequisites
- Node.js 24.14 or later and Corepack for pnpm.
- An existing Amplitude test project, its ingestion API key, and its US or EU data center. Open Organization settings > API Keys and select the test project.
This uses Node24's built-in SQLite API, which is experimental in the tested runtime. No hosted database account is needed.
No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. Sign up for free to get your project API key.
1. Create the standalone project
I'll install the Node.js analytics SDK and use pinned versions from the tested example.
mkdir nodejs-activation
cd nodejs-activation
mkdir -p src tests
corepack enable{
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"name": "amplitude-nodejs-activation",
"engines": {
"node": ">=24.14.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"test": "node --test tests/*.test.mjs",
"demo": "node --env-file-if-exists=.env.local src/cli.js"
},
"dependencies": {
"@amplitude/analytics-node": "1.5.82"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradenode_modules/
.env.local
data/AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_DB_PATH=data/activation.sqlitecorepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.localSet AMPLITUDE_API_KEY to the test-project ingestion key and AMPLITUDE_SERVER_ZONE to US or EU. The project key has the minimum scope needed to ingest data. Keep your local environment file out of source control. These examples never need an Amplitude secret key.
In an existing app, merge these additions into the current SDK entry point and business operations. Preserve authentication, consent, routes and other instrumentation; use the authenticated account ID rather than accepting an arbitrary client-supplied user ID.
2. Commit activation with the business operation
I'll use SQLite transactions to commit the first saved record and activation together. The unique user key prevents concurrent operations from creating multiple activation rows. Record values stay in the local database.
import { DatabaseSync } from 'node:sqlite';
import { randomUUID } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export function openStore(path) {
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path, { timeout: 5000 });
db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS workspaces (user_id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS records (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS activations (user_id TEXT PRIMARY KEY, insert_id TEXT NOT NULL UNIQUE, occurred_at INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0);`);
return db;
}
export function applyOperation(db, userId, operation, value = '') {
if (!/^build-activation-[a-z0-9-]{5,80}$/.test(userId)) throw new Error('Use a synthetic build-activation- ID.');
if (!['workspace', 'record'].includes(operation)) throw new Error('Unknown operation.');
if (operation === 'record' && (!value || value.length > 100)) throw new Error('Record needs 1-100 characters.');
db.exec('BEGIN IMMEDIATE');
try {
if (operation === 'workspace') db.prepare('INSERT OR IGNORE INTO workspaces VALUES (?)').run(userId);
else {
if (!db.prepare('SELECT user_id FROM workspaces WHERE user_id = ?').get(userId)) throw new Error('Create the workspace first.');
db.prepare('INSERT INTO records VALUES (?, ?, ?)').run(randomUUID(), userId, value);
}
const ready = db.prepare('SELECT COUNT(*) AS n FROM records WHERE user_id = ?').get(userId).n > 0;
if (ready) db.prepare('INSERT OR IGNORE INTO activations(user_id,insert_id,occurred_at) VALUES (?,?,?)').run(userId, randomUUID(), Date.now());
db.exec('COMMIT');
return { operation, activated: ready };
} catch (error) { db.exec('ROLLBACK'); throw error; }
}
export function pending(db) { return db.prepare('SELECT user_id,insert_id,occurred_at FROM activations WHERE sent=0 ORDER BY occurred_at').all(); }
export async function deliverPending(db, send) {
const results = [];
for (const row of pending(db)) {
if (Date.now() - row.occurred_at >= 7 * 24 * 60 * 60 * 1000) throw new Error('Activation outbox exceeds the deduplication window; reconcile before replay.');
const code = await send({ event_type: 'Workspace Activated', user_id: row.user_id,
device_id: row.user_id, insert_id: row.insert_id, time: row.occurred_at,
event_properties: { activation_rule: 'workspace_first_record_v1' } });
if (code === 200) db.prepare('UPDATE activations SET sent=1 WHERE insert_id=?').run(row.insert_id);
results.push({ insert_id: row.insert_id, code });
}
return results;
}workspace creates a local workspace row. record requires that workspace and saves a real record. Activation means the workspace has at least one committed record. This rule belongs to the demo; choose an outcome that reflects value in your own product.
Why. A check in application memory disappears on restart and races across processes. BEGIN IMMEDIATE serializes competing writes; the activation row's unique key holds across restarts. The event ID and timestamp are created only for the first committed transition.
The outbox remains at-least-once. Two delivery workers can select the same pending row. Amplitude deduplicates matching device/insert IDs within seven days; that is a bounded ingestion rule, not permanent exactly-once delivery. The fixture stops rows seven days old for manual reconciliation rather than replaying them indefinitely.
3. Flush a pending event and inspect its result
I'll initialize one client for the delivery command, queue each saved event, explicitly flush, then read its result. The Node.js SDK reference distinguishes a completed flush from a successful per-event upload.
export async function createSender(env = process.env) {
if (!env.AMPLITUDE_API_KEY?.trim()) return null;
const { createInstance } = await import('@amplitude/analytics-node');
const client = createInstance();
await client.init(env.AMPLITUDE_API_KEY.trim(), {
serverZone: env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
flushIntervalMillis: 1000, flushQueueSize: 100,
flushMaxRetries: 0, requestTimeoutMillis: 5000,
}).promise;
return async (event) => {
const queued = client.track(event);
await client.flush().promise;
return (await queued.promise).code;
};
}A blank key returns before importing or initializing the SDK. An accepted result with code200 marks the row sent. Other codes leave it pending, and exceptions stop the command while preserving pending state. The business record was already committed.
The one-second queue interval, queue size100, zero SDK retries and five-second request timeout are explicit example settings. Retry means running the delivery command again with the same saved event. Add an operational retry policy and worker leasing before adapting this small fixture to a production service.
4. Keep business commands separate from delivery
I'll run business operations without a network dependency and deliver the outbox as a separate command. The synthetic ID is deliberately restricted for this fixture. It represents a stable user, not an account group.
import { openStore, applyOperation, deliverPending, pending } from './store.js';
import { createSender } from './analytics.js';
const [operation, userId, value] = process.argv.slice(2);
const db = openStore(process.env.BUILD_DB_PATH || 'data/activation.sqlite');
try {
if (operation === 'deliver') {
const send = await createSender();
console.log(send ? { uploads: await deliverPending(db, send) } : { analytics: 'disabled', pending: pending(db).length });
} else console.log(applyOperation(db, userId, operation, value));
} catch (error) { console.error(error.message); process.exitCode = 1; }
finally { db.close(); }A real service should derive user identity from its authenticated context. Here the synthetic ID is passed explicitly as both user_id and device_id, so no undocumented server-side device default is needed. No record text, file path or credential is included in the event.
5. Test and run the example
The tests reopen the database, exercise rollback and failed delivery, reject outbox rows outside the retry window, and start four concurrent record-writing processes.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawn } from 'node:child_process';
import { openStore, applyOperation, deliverPending, pending } from '../src/store.js';
const user = 'build-activation-test-user';
test('rollback, durable state and stable failed-send retry', async () => {
const dir = await mkdtemp(join(tmpdir(), 'activation-')); const path = join(dir,'db.sqlite');
let db = openStore(path);
try {
assert.throws(() => applyOperation(db,user,'record','private marker'));
assert.equal(pending(db).length,0);
applyOperation(db,user,'workspace'); assert.equal(pending(db).length,0);
applyOperation(db,user,'record','PRIVATE_ACTIVATION_FIXTURE');
const first = pending(db)[0]; db.close(); db = openStore(path);
assert.deepEqual(pending(db)[0],first);
const bodies=[]; await deliverPending(db,async e=>{bodies.push(e);return 500;});
assert.equal(pending(db).length,1);
await deliverPending(db,async e=>{bodies.push(e);return 200;});
assert.equal(pending(db).length,0); assert.deepEqual(bodies[0],bodies[1]);
db.prepare('UPDATE activations SET sent=0, occurred_at=?').run(Date.now()-8*86400000);
await assert.rejects(deliverPending(db,async()=>200),/deduplication window/);
db.prepare('UPDATE activations SET sent=1').run();
assert.ok(!JSON.stringify(bodies).includes('PRIVATE_ACTIVATION_FIXTURE'));
applyOperation(db,user,'record','second'); assert.equal(pending(db).length,0);
} finally { db.close(); await rm(dir,{recursive:true,force:true}); }
});
test('concurrent processes commit all records but one activation', async () => {
const dir=await mkdtemp(join(tmpdir(),'activation-')); const path=join(dir,'db.sqlite');
let db=openStore(path); applyOperation(db,user,'workspace');db.close();
const run=()=>new Promise((resolve,reject)=>{
const child=spawn(process.execPath,['src/cli.js','record',user,'synthetic'],{cwd:new URL('../',import.meta.url),env:{...process.env,BUILD_DB_PATH:path,AMPLITUDE_API_KEY:''},stdio:['ignore','pipe','pipe']});
let stderr=''; child.stderr.on('data',d=>stderr+=d);child.on('error',reject);child.on('exit',code=>code===0?resolve():reject(Error(stderr)));
});
try { await Promise.all([run(),run(),run(),run()]);db=openStore(path);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,4);
assert.equal(pending(db).length,1);
} finally { db?.close();await rm(dir,{recursive:true,force:true}); }
});pnpm test
pnpm demo workspace build-activation-example
pnpm demo record build-activation-example synthetic-record
pnpm demo deliver
pnpm demo record build-activation-example second-record
pnpm demo deliverVerify it worked
Choose a fresh synthetic user ID for a new end-to-end run. Keep the same ID through its operations.
- Business state: Create the workspace, then run deliver. There should be no activation upload yet. Save the first record and run deliver again. With a valid test key, the command reports one code200. Save another record and deliver: there should be no new pending activation.
- Restart and blank key: With a fresh database and no key, create a workspace and record, then deliver. It reports disabled with one pending row. Add the key and run deliver again; the durable pending event is still available.
- Failure and retry: Run the tests. The simulated500 leaves the row pending and the later200 uses an identical event. Four concurrent business processes save four records and create one activation. The expired-row check stops replay beyond the bounded window.
- Processed outcome: Search the synthetic user ID in User Lookup and inspect Activity. Allow ten seconds to one minute. Confirm one
Workspace Activatedwithactivation_rule: workspace_first_record_v1. Inspect the full raw event for the synthetic record marker; no record value should appear. HTTP acceptance alone is not a processed-history check. - Live duplicate check: In an isolated test database only, replay the same pending event without changing its device ID, insert ID or timestamp. Confirm both attempts return200 but processed history has one activation. Do this within seven days and retain the original event identifiers.
Troubleshooting
The delivery command leaves a pending row
Check the reported code and the test-project key/data center. An upload error does not roll back the workspace record. Retry the same row within the supported window; do not mint a replacement ID after an ambiguous result.
A later record does not send another activation
Activation is one transition for this rule and user. Use a new synthetic user for a new test, not a fresh event ID on every save.
SQLite is busy or experimental
The example uses a five-second busy timeout and short transactions. Keep network work outside the write transaction. Node24 prints an experimental SQLite warning; evaluate that runtime choice before production use.
An outbox row exceeds the deduplication window
Reconcile the saved event against processed history before deciding how to recover. The fixture deliberately stops rather than promising indefinite deduplication.
Full code reference
The complete runnable example includes the lockfile. These are the complete setup, application and test files.
===== package.json =====
{
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"name": "amplitude-nodejs-activation",
"engines": {
"node": ">=24.14.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"test": "node --test tests/*.test.mjs",
"demo": "node --env-file-if-exists=.env.local src/cli.js"
},
"dependencies": {
"@amplitude/analytics-node": "1.5.82"
}
}
===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade
===== .gitignore =====
node_modules/
.env.local
data/
===== .env.example =====
AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_DB_PATH=data/activation.sqlite
===== src/store.js =====
import { DatabaseSync } from 'node:sqlite';
import { randomUUID } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export function openStore(path) {
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path, { timeout: 5000 });
db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS workspaces (user_id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS records (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS activations (user_id TEXT PRIMARY KEY, insert_id TEXT NOT NULL UNIQUE, occurred_at INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0);`);
return db;
}
export function applyOperation(db, userId, operation, value = '') {
if (!/^build-activation-[a-z0-9-]{5,80}$/.test(userId)) throw new Error('Use a synthetic build-activation- ID.');
if (!['workspace', 'record'].includes(operation)) throw new Error('Unknown operation.');
if (operation === 'record' && (!value || value.length > 100)) throw new Error('Record needs 1-100 characters.');
db.exec('BEGIN IMMEDIATE');
try {
if (operation === 'workspace') db.prepare('INSERT OR IGNORE INTO workspaces VALUES (?)').run(userId);
else {
if (!db.prepare('SELECT user_id FROM workspaces WHERE user_id = ?').get(userId)) throw new Error('Create the workspace first.');
db.prepare('INSERT INTO records VALUES (?, ?, ?)').run(randomUUID(), userId, value);
}
const ready = db.prepare('SELECT COUNT(*) AS n FROM records WHERE user_id = ?').get(userId).n > 0;
if (ready) db.prepare('INSERT OR IGNORE INTO activations(user_id,insert_id,occurred_at) VALUES (?,?,?)').run(userId, randomUUID(), Date.now());
db.exec('COMMIT');
return { operation, activated: ready };
} catch (error) { db.exec('ROLLBACK'); throw error; }
}
export function pending(db) { return db.prepare('SELECT user_id,insert_id,occurred_at FROM activations WHERE sent=0 ORDER BY occurred_at').all(); }
export async function deliverPending(db, send) {
const results = [];
for (const row of pending(db)) {
if (Date.now() - row.occurred_at >= 7 * 24 * 60 * 60 * 1000) throw new Error('Activation outbox exceeds the deduplication window; reconcile before replay.');
const code = await send({ event_type: 'Workspace Activated', user_id: row.user_id,
device_id: row.user_id, insert_id: row.insert_id, time: row.occurred_at,
event_properties: { activation_rule: 'workspace_first_record_v1' } });
if (code === 200) db.prepare('UPDATE activations SET sent=1 WHERE insert_id=?').run(row.insert_id);
results.push({ insert_id: row.insert_id, code });
}
return results;
}
===== src/analytics.js =====
export async function createSender(env = process.env) {
if (!env.AMPLITUDE_API_KEY?.trim()) return null;
const { createInstance } = await import('@amplitude/analytics-node');
const client = createInstance();
await client.init(env.AMPLITUDE_API_KEY.trim(), {
serverZone: env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
flushIntervalMillis: 1000, flushQueueSize: 100,
flushMaxRetries: 0, requestTimeoutMillis: 5000,
}).promise;
return async (event) => {
const queued = client.track(event);
await client.flush().promise;
return (await queued.promise).code;
};
}
===== src/cli.js =====
import { openStore, applyOperation, deliverPending, pending } from './store.js';
import { createSender } from './analytics.js';
const [operation, userId, value] = process.argv.slice(2);
const db = openStore(process.env.BUILD_DB_PATH || 'data/activation.sqlite');
try {
if (operation === 'deliver') {
const send = await createSender();
console.log(send ? { uploads: await deliverPending(db, send) } : { analytics: 'disabled', pending: pending(db).length });
} else console.log(applyOperation(db, userId, operation, value));
} catch (error) { console.error(error.message); process.exitCode = 1; }
finally { db.close(); }
===== tests/store.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawn } from 'node:child_process';
import { openStore, applyOperation, deliverPending, pending } from '../src/store.js';
const user = 'build-activation-test-user';
test('rollback, durable state and stable failed-send retry', async () => {
const dir = await mkdtemp(join(tmpdir(), 'activation-')); const path = join(dir,'db.sqlite');
let db = openStore(path);
try {
assert.throws(() => applyOperation(db,user,'record','private marker'));
assert.equal(pending(db).length,0);
applyOperation(db,user,'workspace'); assert.equal(pending(db).length,0);
applyOperation(db,user,'record','PRIVATE_ACTIVATION_FIXTURE');
const first = pending(db)[0]; db.close(); db = openStore(path);
assert.deepEqual(pending(db)[0],first);
const bodies=[]; await deliverPending(db,async e=>{bodies.push(e);return 500;});
assert.equal(pending(db).length,1);
await deliverPending(db,async e=>{bodies.push(e);return 200;});
assert.equal(pending(db).length,0); assert.deepEqual(bodies[0],bodies[1]);
db.prepare('UPDATE activations SET sent=0, occurred_at=?').run(Date.now()-8*86400000);
await assert.rejects(deliverPending(db,async()=>200),/deduplication window/);
db.prepare('UPDATE activations SET sent=1').run();
assert.ok(!JSON.stringify(bodies).includes('PRIVATE_ACTIVATION_FIXTURE'));
applyOperation(db,user,'record','second'); assert.equal(pending(db).length,0);
} finally { db.close(); await rm(dir,{recursive:true,force:true}); }
});
test('concurrent processes commit all records but one activation', async () => {
const dir=await mkdtemp(join(tmpdir(),'activation-')); const path=join(dir,'db.sqlite');
let db=openStore(path); applyOperation(db,user,'workspace');db.close();
const run=()=>new Promise((resolve,reject)=>{
const child=spawn(process.execPath,['src/cli.js','record',user,'synthetic'],{cwd:new URL('../',import.meta.url),env:{...process.env,BUILD_DB_PATH:path,AMPLITUDE_API_KEY:''},stdio:['ignore','pipe','pipe']});
let stderr=''; child.stderr.on('data',d=>stderr+=d);child.on('error',reject);child.on('exit',code=>code===0?resolve():reject(Error(stderr)));
});
try { await Promise.all([run(),run(),run(),run()]);db=openStore(path);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,4);
assert.equal(pending(db).length,1);
} finally { db?.close();await rm(dir,{recursive:true,force:true}); }
});Hand it to your agent
Use https://amplitude.com/build/nodejs-activation and its linked source.
Inspect the existing application and SDK entry point first. Preserve auth, consent,
and other instrumentation. Read the installed SDK's current docs through Docs MCP.
Commit the first meaningful activation transition and its outbox row atomically.
Use a database uniqueness constraint, stable insert/device IDs and original time.
Never send record contents. Keep business writes independent from upload success.
Preserve pending rows on failure, enforce a bounded replay window, and explain
at-least-once delivery. Test concurrent processes, restart, failed sends and retries.
Run local failure and success checks. Verify real HTTP acceptance and processed
history separately. Keep environment secrets and synthetic fixture data local.
Report changed files and remaining coverage limits.MCP. The Docs MCP server reads public documentation. It cannot inspect this project's events or run the application for you.
What this unlocks
Product analytics can count the committed activation outcome rather than every record click.
Session replay can add browser context in a separate client integration; this Node-only fixture records no replay.
Feature flags can vary onboarding while the same stable activation rule measures the result.
Guides and surveys can support onboarding through a separately configured browser integration.
Frequently asked questions
Does this guarantee exactly one delivered event forever?
No. The database commits one activation row; delivery is at-least-once. Amplitude deduplicates a matching device/insert ID within seven days. Long outages and older backlog need a recovery policy.
Does an upload failure undo activation?
No. The local record and outbox transition commit together. Upload runs later; a failure leaves the outbox pending without undoing the business operation.
Why not send the first-record event from a React click?
A click does not establish that the save committed. This example records activation where the backend owns the durable operation.
Next steps
Reference docs
Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.