DEV Community

Cover image for CRM Customization Services: Building Idempotent Sync in Node.js
Sanya Mittal
Sanya Mittal

Posted on

CRM Customization Services: Building Idempotent Sync in Node.js

A CRM webhook fires twice for the same “deal won” event, and your ERP now holds two work orders and two invoices for one sale. This happens whenever a CRM retries delivery after a slow response, which is normal behavior in production. It is also the most common defect we see in CRM customization services that connect a CRM to billing or operations. Below, we show the pattern we use to stop it, and we explain how CRM customization services handle cross-system events in a live media platform.

Context and Setup

In CRM customization services Idempotent sync means that processing the same event any number of times leaves the target system in the same state as processing it once. You need it because webhook delivery is at-least-once, not exactly-once. Stripe’s webhook documentation states that it retries failed live-mode deliveries with exponential backoff for up to three days, and most CRMs follow a similar model.

Our scenario is a Node.js 20 service between a CRM and an ERP. It receives deal.won webhooks, creates a work order in the ERP, and answers within a few seconds. Prerequisites: Express, PostgreSQL 14 or later, and a shared signing secret from the CRM.

Building Reliable Sync for CRM Customization Services

The design has three parts: verify and record the event, acknowledge fast, and process asynchronously with a retry limit.

Step 1: Record the Event Before Doing Any Work

Store the CRM’s event ID first, because a unique constraint is the only duplicate check that survives concurrent deliveries. An in-memory check fails the moment you run two instances.

sql
-- Why: the primary key on event_id makes duplicate inserts impossible
CREATE TABLE sync_events (
event_id text PRIMARY KEY,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending', -- pending | done | dead
attempts int NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now()
);
Step 2: Acknowledge Fast, Process Later

Return a 2xx as soon as the event is stored. Slow responses are what trigger the CRM retries in the first place.

js
import crypto from 'node:crypto';
import express from 'express';

const app = express();

// Why: signature checks need the raw bytes, not re-serialized JSON
app.post('/webhooks/crm', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.get('X-CRM-Signature') ?? '';
const expected = crypto.createHmac('sha256', process.env.CRM_SECRET)
.update(req.body).digest('hex');

// Why: timingSafeEqual blocks timing attacks; length check avoids a thrown error
if (sig.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
return res.sendStatus(401);
}

const event = JSON.parse(req.body);
const { rowCount } = await db.query(
INSERT INTO sync_events (event_id, payload) VALUES ($1, $2)
ON CONFLICT (event_id) DO NOTHING
, // Why: a duplicate delivery inserts zero rows
[event.id, event]
);

// Duplicate or new, the answer is 200 so the CRM stops retrying
res.sendStatus(rowCount === 0 ? 200 : 202);
});

The worker then claims rows safely and passes the event ID to the ERP as its own idempotency key.

js
async function runWorker() {
// Why: SKIP LOCKED lets several workers run without claiming the same row
const { rows } = await db.query(
SELECT event_id, payload FROM sync_events
WHERE status = 'pending' ORDER BY created_at
LIMIT 10 FOR UPDATE SKIP LOCKED
);

for (const ev of rows) {
try {
// Why: the ERP dedupes on this header, so a crash after the call is safe
await erp.createWorkOrder(ev.payload, { idempotencyKey: ev.event_id });
await db.query(UPDATE sync_events SET status='done' WHERE event_id=$1, [ev.event_id]);
} catch (err) {
// Why: after 5 failures a human must look; endless retries hide defects
await db.query(
UPDATE sync_events SET attempts = attempts + 1,
status = CASE WHEN attempts + 1 >= 5 THEN 'dead' ELSE 'pending' END
WHERE event_id=$1
, [ev.event_id]);
}
}
}

Note that the claim and the updates should share one transaction in production. We trimmed that here for length.

Step 3: Trade-Offs in CRM Customization Services

In CRM customization services A table plus a polling worker is the simplest option, and it is easy to debug with plain SQL. A message queue such as SQS scales further, but it adds infrastructure and makes inspection harder. We choose the table until throughput proves otherwise.

The other trade-off is the retry cap. A low cap surfaces bad payloads quickly, while a high cap hides them. In a media operations platform we built at Oodles, work orders, billing, and CRM data had to move between QuickBooks, Infusionsoft, and Authorize.Net without duplicates.

Key Takeaways
Webhook delivery is at-least-once, so every handler must tolerate repeats.
A database unique key on the event ID is the only duplicate check that survives multiple instances.
Verify signatures on raw bytes, and acknowledge before doing slow work.
Pass the event ID downstream as an idempotency key to cover crashes after the ERP call.
Cap retries and keep a dead status, so defects stay visible.

Have a retry or ordering edge case that this pattern does not cover? Share it in the comments, or talk to us about CRM customization services.

What are CRM customization services in a developer context?
CRM customization services extend a CRM with custom objects, workflows, and integrations. For developers, this usually means webhook handlers, API sync jobs, and data validation that connect the CRM to ERP, billing, and operations systems.

What does idempotent mean for a webhook handler?
An idempotent handler produces the same end state whether an event arrives once or ten times. You achieve this by storing a unique event ID and skipping any event whose ID already exists.

Why do CRMs send duplicate webhooks?
Delivery is at-least-once. If your endpoint times out or returns a non-2xx status, the CRM retries, even when your side already processed the event. Duplicates are expected behavior, not a CRM defect.

Should I use a queue or a database table for sync events?
Start with a database table when volume is moderate, because you can inspect and replay rows with SQL. Move to a queue such as SQS when throughput or fan-out outgrows polling.

How many retries should a sync worker attempt?
Five attempts with backoff is a practical default. Fewer retries expose bad payloads sooner, while more retries delay detection. Move exhausted events to a dead status and alert someone instead of retrying forever.

Top comments (0)