<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sanya Mittal</title>
    <description>The latest articles on DEV Community by Sanya Mittal (@sanya_mittal_a509a2c50a2d).</description>
    <link>https://dev.to/sanya_mittal_a509a2c50a2d</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3523639%2Feaa41d0e-95c1-466f-863f-5fa6dcba3804.jpeg</url>
      <title>DEV Community: Sanya Mittal</title>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sanya_mittal_a509a2c50a2d"/>
    <language>en</language>
    <item>
      <title>Fixing Live Video Streaming Stalls After Encoder Drops in Node.js</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Fri, 04 Dec 2026 08:03:43 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/fixing-live-video-streaming-stalls-after-encoder-drops-in-nodejs-j4h</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/fixing-live-video-streaming-stalls-after-encoder-drops-in-nodejs-j4h</guid>
      <description>&lt;p&gt;A field encoder loses its cellular link for four seconds and reconnects. Your origin restarts FFmpeg, the HLS playlist resets its media sequence, and every player freezes on a stale manifest until the viewer refreshes. This failure appears in live video streaming pipelines that ingest from OBS, bonded cellular units, or hardware encoders. It hides well, because the process looks healthy in server metrics. Below, we fix it with a Node.js supervisor, a resumable playlist, and a stall watchdog. For the wider picture, see &lt;a href="https://www.oodles.com/video-streaming/67?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_62" rel="noopener noreferrer"&gt;how video streaming works in production ingest chains&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Short answer: the fix needs three pieces: a playlist that survives restarts, a restart policy, and a stall detector.&lt;/p&gt;

&lt;p&gt;Our scenario is a single-origin live channel. An encoder pushes RTMP to a Docker container running Node.js 20 and FFmpeg 6. FFmpeg writes HLS to a mounted volume, and nginx serves that volume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;The encoder sets a two-second keyframe interval, so -c:v copy can cut segments cleanly.&lt;br&gt;
The HLS directory sits on a volume that outlives the container.&lt;br&gt;
nginx sends Cache-Control: no-cache for the .m3u8 file only.&lt;/p&gt;

&lt;p&gt;Why bother? Conviva's 2019 data, reported by Streaming Media, found that live streams failed to start 2.6 percent of the time, against 1.5 percent for on-demand. Live paths have more moving parts, and encoder reconnects are one of them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keeping Video Streaming Ingest Alive Across Encoder Drops&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Short answer: run FFmpeg as a disposable process under a supervisor, and make its output safe to resume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Make the Playlist Resumable&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;video streaming Use the append_list and discont_start HLS flags. Without append_list, FFmpeg rewrites the playlist from segment zero. A player holding sequence 412 then sees a manifest that starts at 0 and cannot continue. With append_list, FFmpeg continues the media sequence. discont_start adds an EXT-X-DISCONTINUITY tag, so players reset their decoders at the splice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Supervise FFmpeg With Backoff and a Watchdog&lt;/strong&gt;&lt;br&gt;
Start FFmpeg in listen mode, so one encoder session equals one process.&lt;br&gt;
On exit, restart with exponential backoff capped at eight seconds.&lt;br&gt;
Reset the backoff after a run longer than 60 seconds.&lt;br&gt;
Kill FFmpeg if the playlist stops updating while the process stays alive.&lt;br&gt;
js&lt;br&gt;
// ingest-supervisor.mjs (Node 20+, FFmpeg 6+)&lt;br&gt;
import { spawn } from "node:child_process";&lt;br&gt;
import { stat } from "node:fs/promises";&lt;/p&gt;

&lt;p&gt;const PLAYLIST = "/var/hls/live.m3u8"; // Why: lives on a volume, so it survives container restarts&lt;br&gt;
const STALL_MS = 15_000;&lt;br&gt;
const MAX_BACKOFF_MS = 8_000;&lt;br&gt;
let backoff = 500;&lt;/p&gt;

&lt;p&gt;function startIngest() {&lt;br&gt;
  const startedAt = Date.now();&lt;br&gt;
  const ff = spawn("ffmpeg", [&lt;br&gt;
    "-hide_banner", "-loglevel", "warning",&lt;br&gt;
    "-listen", "1", "-i", "rtmp://0.0.0.0:1935/live/stream", // Why: one encoder session equals one process&lt;br&gt;
    "-c:v", "copy", "-c:a", "aac",                           // Why: no video re-encode keeps CPU flat&lt;br&gt;
    "-f", "hls", "-hls_time", "4", "-hls_list_size", "6",&lt;br&gt;
    "-hls_flags", "delete_segments+append_list+discont_start", // Why: continue the sequence, mark the splice&lt;br&gt;
    "-hls_segment_filename", "/var/hls/seg_%d.ts",&lt;br&gt;
    PLAYLIST,&lt;br&gt;
  ], { stdio: ["ignore", "inherit", "inherit"] });&lt;/p&gt;

&lt;p&gt;// Why: a hung socket keeps ffmpeg alive but stops segment output&lt;br&gt;
  const watchdog = setInterval(async () =&amp;gt; {&lt;br&gt;
    try {&lt;br&gt;
      const { mtimeMs } = await stat(PLAYLIST);&lt;br&gt;
      const stale = Date.now() - mtimeMs &amp;gt; STALL_MS;&lt;br&gt;
      // Why: only judge runs that already wrote output, so idle listening is not killed&lt;br&gt;
      if (stale &amp;amp;&amp;amp; mtimeMs &amp;gt; startedAt) ff.kill("SIGKILL");&lt;br&gt;
    } catch { /* playlist not written yet */ }&lt;br&gt;
  }, 5_000);&lt;/p&gt;

&lt;p&gt;ff.on("exit", (code, signal) =&amp;gt; {&lt;br&gt;
    clearInterval(watchdog);&lt;br&gt;
    // Why: a run longer than 60 s counts as healthy, so the delay resets&lt;br&gt;
    backoff = Date.now() - startedAt &amp;gt; 60_000 ? 500 : Math.min(backoff * 2, MAX_BACKOFF_MS);&lt;br&gt;
    console.warn(&lt;code&gt;ffmpeg exited (${code ?? signal}), restarting in ${backoff} ms&lt;/code&gt;);&lt;br&gt;
    setTimeout(startIngest, backoff);&lt;br&gt;
  });&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;startIngest();&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Weigh Video Streaming Ingest Trade-offs&lt;/strong&gt;&lt;br&gt;
Listen-mode FFmpeg versus a dedicated RTMP server: FFmpeg means fewer components, but it exits on every drop, so the supervisor carries reliability. A dedicated server keeps the listener open but adds a second component to patch and monitor.&lt;br&gt;
Copy versus transcode: copying video keeps CPU flat but depends on aligned keyframes. Transcoding normalizes input and costs CPU and latency.&lt;br&gt;
Discontinuity versus hot failover: this setup recovers within seconds and shows one rebuffer. Zero-gap failover needs dual ingest and an origin that switches sources.&lt;br&gt;
Segment length: four-second segments with a six-entry list give a 24-second window. Shorter segments recover faster but raise request volume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our video streaming projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a live news channel ingested from field encoders over cellular links. Every drop reset the HLS sequence, and viewers had to refresh manually. We moved ingest under a Node.js supervisor with a resumable playlist and a stall watchdog, as shown above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
A restarted packager that resets the media sequence strands players, so continue the playlist with append_list.&lt;br&gt;
discont_start tells players to reset decoder state at the splice instead of failing on a timestamp jump.&lt;br&gt;
Treat FFmpeg as disposable, and put reliability in a supervisor with capped exponential backoff.&lt;br&gt;
A live process can be alive and useless, so watch playlist modification time, not just process state.&lt;br&gt;
Zero-gap recovery needs dual ingest, which costs more than this single-origin design.&lt;/p&gt;

&lt;p&gt;Running a different ingest stack or hitting a different failure? Ask in the comments, or reach us about &lt;a href="//oodles.com/contact-us"&gt;video streaming&lt;/a&gt; architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the best protocol for live video streaming ingest?&lt;/strong&gt;&lt;br&gt;
RTMP remains the most widely supported ingest protocol for encoders. SRT handles lossy networks better through retransmission. Choose RTMP for compatibility and SRT when contribution travels over cellular or long-haul links. Delivery to viewers is a separate decision, usually HLS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does my HLS stream stall after the encoder reconnects?&lt;/strong&gt;&lt;br&gt;
Players track the media sequence number. If the packager restarts and resets it to zero, the player sees a manifest older than its position and waits. Appending to the existing playlist and marking a discontinuity lets playback continue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does EXT-X-DISCONTINUITY do?&lt;/strong&gt;&lt;br&gt;
It signals that the next segment may differ in timestamps, codec parameters, or encoding sequence. The player resets its decoder state at that boundary instead of failing on a timestamp jump.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I make FFmpeg restart automatically?&lt;/strong&gt;&lt;br&gt;
Run it under a supervisor such as a Node.js child process manager, systemd, or a Docker restart policy. Add exponential backoff to prevent crash loops, and a watchdog that kills the process when output files stop updating.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How long should HLS segments be for live video streaming?&lt;/strong&gt;&lt;br&gt;
Four to six seconds is a common balance. Shorter segments lower latency and speed recovery after a drop, but they raise request volume and playlist churn. Measure on your slowest supported device before committing.&lt;/p&gt;

</description>
      <category>node</category>
      <category>ai</category>
      <category>webdev</category>
      <category>productivity</category>
    </item>
    <item>
      <title>How to Build Idempotent Salesforce Upserts in Node.js</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Wed, 02 Dec 2026 07:11:14 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-idempotent-salesforce-upserts-in-nodejs-3kn1</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-idempotent-salesforce-upserts-in-nodejs-3kn1</guid>
      <description>&lt;p&gt;A payment webhook fires twice, your Node.js worker retries after a timeout, and Salesforce now holds two Opportunity records for one invoice. Reps then see inflated pipeline, and finance sees double revenue. This happens wherever a service writes over the REST API without a stable key, usually in webhook consumers and queue workers that retry on failure. Retries are routine in distributed systems, so these duplicates keep coming. The fix is to stop creating records and start upserting them against an external ID. This article shows &lt;a href="https://www.oodles.com/salesforce?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_60" rel="noopener noreferrer"&gt;how Salesforce integrations work in production with a retry-safe Node.js client&lt;/a&gt;, covering field setup, the upsert call, and retry rules.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A safe retry needs three things: a unique external ID field, a stable key from the source system, and a policy that repeats only errors that are safe to repeat.&lt;/p&gt;

&lt;p&gt;You need Node.js 18 or later (for built-in fetch), an OAuth access token from a connected app, and API version 61.0. Retries also cost quota. API Request Limits documentation states that the daily allocation applies to the whole org, not per user. Its own example is an Enterprise Edition org with 15 licenses, which gets 115,000 requests per rolling 24 hours. Past that, calls fail with HTTP 403 and REQUEST_LIMIT_EXCEEDED.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Make Salesforce Writes Idempotent With External IDs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An idempotent write gives the same final state whether it runs once or five times. Upsert on an external ID provides that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create a Unique External ID Field&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A unique constraint lets the database reject duplicates even when two workers race.&lt;/p&gt;

&lt;p&gt;Open Setup, then Object Manager, then Opportunity.&lt;br&gt;
Create a Text(40) field named Billing_Ref__c.&lt;br&gt;
Tick both External ID and Unique.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Upsert by Key in Node.js&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A PATCH request to an external ID path creates the record if the key is new and updates it if the key exists.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// upsert.js (Node.js 18+, built-in fetch)&lt;br&gt;
const API = 'v61.0';&lt;/p&gt;

&lt;p&gt;export async function upsertOpportunity(ctx, invoice) {&lt;br&gt;
  // Why: the invoice ID is the idempotency key, so a retry updates instead of duplicating&lt;br&gt;
  const url = &lt;code&gt;${ctx.instanceUrl}/services/data/${API}&lt;/code&gt; +&lt;br&gt;
    &lt;code&gt;/sobjects/Opportunity/Billing_Ref__c/${encodeURIComponent(invoice.id)}&lt;/code&gt;;&lt;/p&gt;

&lt;p&gt;const res = await fetch(url, {&lt;br&gt;
    method: 'PATCH', // Why: PATCH on an external ID path is the REST upsert&lt;br&gt;
    headers: {&lt;br&gt;
      Authorization: &lt;code&gt;Bearer ${ctx.accessToken}&lt;/code&gt;,&lt;br&gt;
      'Content-Type': 'application/json',&lt;br&gt;
    },&lt;br&gt;
    // Why: the key is already in the URL, so it stays out of the body&lt;br&gt;
    body: JSON.stringify({&lt;br&gt;
      Name: &lt;code&gt;Invoice ${invoice.id}&lt;/code&gt;,&lt;br&gt;
      Amount: invoice.amount,&lt;br&gt;
      StageName: 'Closed Won',&lt;br&gt;
      CloseDate: invoice.paidOn, // YYYY-MM-DD&lt;br&gt;
    }),&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;// 201 means created, 204 means updated&lt;br&gt;
  if (res.status === 201 || res.status === 204) return res.status;&lt;br&gt;
  const errors = await res.json().catch(() =&amp;gt; []);&lt;br&gt;
  throw Object.assign(new Error('Salesforce upsert failed'), { status: res.status, errors });&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Step 3: Retry Only Safe Errors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Retry only errors that clear on their own. Row locks clear in milliseconds, while a quota error clears in hours.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
const RETRYABLE = new Set(['UNABLE_TO_LOCK_ROW', 'SERVER_UNAVAILABLE']);&lt;/p&gt;

&lt;p&gt;export async function withRetry(fn, max = 4) {&lt;br&gt;
  for (let attempt = 0; ; attempt++) {&lt;br&gt;
    try {&lt;br&gt;
      return await fn();&lt;br&gt;
    } catch (err) {&lt;br&gt;
      const code = err.errors?.[0]?.errorCode;&lt;br&gt;
      // Why: fetch throws TypeError on network failure, and upsert makes that retry safe&lt;br&gt;
      const safe = RETRYABLE.has(code) || err.status &amp;gt;= 500 || err instanceof TypeError;&lt;br&gt;
      // Why: REQUEST_LIMIT_EXCEEDED will not clear in seconds, so retrying only burns quota&lt;br&gt;
      if (!safe || attempt &amp;gt;= max) throw err;&lt;br&gt;
      // Why: jitter stops parallel workers from retrying in lockstep and re-locking the row&lt;br&gt;
      const delay = Math.min(8000, 250 * 2 ** attempt) * (0.5 + Math.random());&lt;br&gt;
      await new Promise((r) =&amp;gt; setTimeout(r, delay));&lt;br&gt;
    }&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Trade-offs:&lt;/p&gt;

&lt;p&gt;Upsert versus query-then-insert: the query adds a second API call and leaves a race window between the check and the write.&lt;br&gt;
Single upsert versus sObject Collections: collections handle up to 200 records per call and save quota, but you must read per-record results, since one bad row no longer fails the whole request.&lt;br&gt;
Real-World Application&lt;/p&gt;

&lt;p&gt;In one of our projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a real estate synced 1000 invoices per day from a quickbooks into Opportunities through a Node.js worker. Timeout retries created duplicate records at a rate of 70 percent. We added the unique external ID, switched inserts to upserts, and batched writes through sObject Collections with the retry policy above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
A unique external ID field turns a database constraint into your last line of defense against duplicate writes.&lt;br&gt;
PATCH on an external ID path gives you one-call upsert, so no read-before-write race exists.&lt;br&gt;
Quota errors and lock errors need different retry rules, because one clears in milliseconds and the other in hours.&lt;br&gt;
Collections cut call counts, at the cost of per-record error handling.&lt;/p&gt;

&lt;p&gt;Questions or edge cases from your own integration? Share them in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;Salesforce&lt;/a&gt; integration work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I prevent duplicate records in the REST API?&lt;/strong&gt;&lt;br&gt;
Add a unique external ID field, store the source system's stable key in it, and write with PATCH on the external ID path. Retries then update the existing record, and the unique constraint blocks races between workers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I retry REQUEST_LIMIT_EXCEEDED?&lt;/strong&gt;&lt;br&gt;
Not quickly. It returns HTTP 403 when the rolling 24-hour allocation or the concurrent long-running request cap is hit. Queue the work, check the /limits resource, and resume once usage falls back under the allocation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the difference between insert and upsert in It?&lt;/strong&gt;&lt;br&gt;
Insert always creates a record. Upsert checks an ID or external ID, then updates the match or creates a new record. Upsert is the safer choice for integrations that may deliver the same message more than once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How many records can one Salesforce API call upsert?&lt;/strong&gt;&lt;br&gt;
sObject Collections accept up to 200 records per call. For larger loads, Bulk API 2.0 processes records asynchronously in jobs, which suits migrations better than real-time sync. Poll the job for results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does Salesforce return UNABLE_TO_LOCK_ROW?&lt;/strong&gt;&lt;br&gt;
Concurrent transactions are updating the same record or a shared parent, such as many Opportunities under one Account. Retry with jittered backoff, and serialize writes per parent key when contention persists.&lt;/p&gt;

</description>
      <category>salesforce</category>
      <category>crm</category>
      <category>agentfoce</category>
      <category>ai</category>
    </item>
    <item>
      <title>Odoo Development Services: Idempotent Webhook Receivers in Odoo 18</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Tue, 01 Dec 2026 07:13:47 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/odoo-development-services-idempotent-webhook-receivers-in-odoo-18-3he5</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/odoo-development-services-idempotent-webhook-receivers-in-odoo-18-3he5</guid>
      <description>&lt;p&gt;A payment gateway retries a failed webhook for days, and your Odoo endpoint treats every retry as a new payment. The result is duplicate postings, double stock reservations, and finance teams reconciling by hand. This happens whenever an external system calls an Odoo controller and the response is slow or lost. Odoo development services for integrations must assume that every inbound call can arrive more than once. This article shows the pattern we use in Odoo 18 with Python and PostgreSQL, drawn from &lt;a href="https://www.oodles.com/odoo-implementation/video/ecom-express?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_59" rel="noopener noreferrer"&gt;how Odoo development services handle integrations in production&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The scenario is a gateway posting JSON events to /webhook/payments, an Odoo 18 database on PostgreSQL, and a sale order that must become paid exactly once. Delivery guarantees are the root issue. Stripe retries live-mode webhook deliveries for up to three days with exponential backoff, and it does not guarantee event order (Stripe documentation, 2026).&lt;/p&gt;

&lt;p&gt;You need a custom addon, the gateway's signing secret stored in ir.config_parameter, and an event payload that carries a stable unique ID.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Odoo Development Services Make Webhook Handlers Idempotent&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Idempotent means the same event produces the same result however many times it arrives. In Odoo, the reliable way to get that is a unique database constraint, not a Python existence check.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Store Every Event Behind a Unique Constraint&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A check-then-insert pattern races. Two retries arriving together can both run search(), find nothing, and both process the event. A unique index closes that gap, because the second insert waits for the first transaction and then fails.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from odoo import fields, models&lt;/p&gt;

&lt;p&gt;class WebhookEvent(models.Model):&lt;br&gt;
    _name = "webhook.event"&lt;br&gt;
    _description = "Inbound webhook event"&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;provider = fields.Char(required=True)
event_id = fields.Char(required=True)

# Why: PostgreSQL, not Python, decides which concurrent delivery wins
_sql_constraints = [
    ("event_uniq", "unique(provider, event_id)", "Event already received"),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Verify, Deduplicate, and Process in One Transaction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The controller does four things in order:&lt;/p&gt;

&lt;p&gt;Verify the HMAC signature against the raw request body.&lt;br&gt;
Insert the event row inside a savepoint.&lt;br&gt;
On a unique violation, return 200 so the sender stops retrying.&lt;br&gt;
Otherwise apply the business change in the same transaction.&lt;br&gt;
python&lt;br&gt;
import hashlib, hmac, json&lt;br&gt;
import psycopg2.errors&lt;br&gt;
from odoo import http&lt;br&gt;
from odoo.http import request&lt;br&gt;
from odoo.tools import mute_logger&lt;/p&gt;

&lt;p&gt;class PaymentWebhook(http.Controller):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@http.route("/webhook/payments", type="http", auth="public",
            methods=["POST"], csrf=False)
def receive(self):
    raw = request.httprequest.get_data()  # Why: signature covers raw bytes, not parsed JSON
    env = request.env(su=True)
    secret = env["ir.config_parameter"].get_param("payments.webhook_secret", "")
    expected = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
    sent = request.httprequest.headers.get("X-Signature", "")
    if not hmac.compare_digest(expected, sent):  # Why: constant-time compare blocks timing attacks
        return request.make_response("invalid signature", status=401)

    event = json.loads(raw)
    try:
        # Why: the savepoint keeps a failed insert from aborting the outer transaction
        with mute_logger("odoo.sql_db"), env.cr.savepoint():
            env["webhook.event"].create(
                {"provider": "payments", "event_id": event["id"]})
    except psycopg2.errors.UniqueViolation:
        return request.make_response("duplicate", status=200)  # Why: 2xx stops sender retries

    # Why: an exception here rolls back the event row too, so the next retry runs clean
    env["sale.order"]._apply_payment_event(event)
    return request.make_response("ok", status=200)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Weigh Trade-offs in Odoo Development Services&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Inline processing keeps the event row and the business change atomic, but the sender's timeout limits how much work fits in the request. For heavier work, store the event and hand it to a queue such as OCA queue_job. The cost is that deduplication and state changes become separate steps.&lt;/p&gt;

&lt;p&gt;Because delivery order is not guaranteed, write _apply_payment_event to compare state transitions, not arrival times. Also schedule a cron job that purges old event rows so the table stays small.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Odoo development projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a client saw duplicate payment postings after gateway retries. We added the event table, the signature check, and the single-transaction handler described above. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Put idempotency in a PostgreSQL unique constraint, because a Python existence check races under concurrent retries.&lt;br&gt;
Verify HMAC signatures on the raw request bytes before parsing JSON.&lt;br&gt;
Wrap the event insert in a savepoint so a duplicate does not abort the outer transaction.&lt;br&gt;
Return 2xx for duplicates and non-2xx for real failures, so rollback and retry stay consistent.&lt;br&gt;
Design handlers around state transitions, not event timestamps, because delivery order is not guaranteed.&lt;/p&gt;

&lt;p&gt;Have you hit duplicate webhook postings in Odoo? Share your retry setup in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;Odoo development services&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are Odoo development services?&lt;/strong&gt;&lt;br&gt;
Odoo development services cover custom modules, third-party integrations, data migration, reporting, and version upgrades. For integrations, the work includes controllers, API clients, and handlers that stay correct when external systems retry or reorder calls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do webhook providers send duplicate events?&lt;/strong&gt;&lt;br&gt;
In Odoo Development Services Providers retry whenever they receive a non-2xx response, a timeout, or no response. A lost reply therefore looks like a failure, and the same event is delivered again. Receivers must tolerate repeats.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should Odoo webhook handlers use queue_job?&lt;/strong&gt;&lt;br&gt;
Use it when processing exceeds the sender's timeout. Store the event first, enqueue the work, and return 200. Keep the unique constraint on the event table, so duplicate deliveries never create duplicate jobs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I secure an Odoo webhook controller?&lt;/strong&gt;&lt;br&gt;
Verify an HMAC signature computed over the raw body, compare it with hmac.compare_digest, and keep the secret in ir.config_parameter. Use separate secrets for test and live endpoints, and reject unexpected event types.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is csrf=False safe on a webhook route?&lt;/strong&gt;&lt;br&gt;
CSRF protects browser sessions, and webhook callers have none. With auth="public", the HMAC signature check replaces CSRF protection. Without that check, csrf=False leaves the endpoint open to forged requests.&lt;/p&gt;

</description>
      <category>odoo</category>
      <category>crm</category>
      <category>erp</category>
      <category>programming</category>
    </item>
    <item>
      <title>How to Validate ERP Software Consultants' Field Mappings with Python</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Fri, 27 Nov 2026 04:41:17 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-validate-erp-software-consultants-field-mappings-with-python-2i51</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-validate-erp-software-consultants-field-mappings-with-python-2i51</guid>
      <description>&lt;p&gt;A migration job dies on a required field that never appeared in the mapping sheet. The sheet came from your ERP software consultants, it looked complete, and nobody compared it with the live schema. This happens during data migration and integration builds, when a spreadsheet becomes the contract between analysts and engineers. This post turns that spreadsheet into a testable artifact that a pipeline can reject. We cover &lt;a href="https://www.oodles.com/custom-erp/video/genesis?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_59" rel="noopener noreferrer"&gt;how ERP software consultants hand off specs in custom ERP builds&lt;/a&gt;, then a short Python check against an Odoo sandbox, then CI gating so a bad spec fails the build before release.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A field mapping spec is trustworthy only if a machine can verify it. Our scenario: consultants deliver a CSV with model, field, and source_type columns, and you hold a sandbox of the target ERP. You need Python 3.10 or newer and a read-only API key. Odoo's XML-RPC API exposes schema metadata through fields_get, and other platforms have equivalents, such as OData $metadata on Dynamics 365.&lt;/p&gt;

&lt;p&gt;ERP software consultants Panorama Consulting Group's 2024 ERP Report found that 35 percent of respondents blamed budget overruns on data issues. A mapping error found in a sandbox costs minutes; mid-migration it costs a cutover window. &lt;br&gt;
informatica&lt;/p&gt;

&lt;p&gt;Auditing ERP Software Consultants' Mappings in Three Steps&lt;/p&gt;

&lt;p&gt;Three steps: get a parseable spec, diff it against the live schema, and fail the build on gaps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Ask ERP Software Consultants for a Machine-Readable Spec&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ask for CSV, not prose, since labels change between versions while technical names stay stable. Require one row per target field:&lt;/p&gt;

&lt;p&gt;model: the technical model name, such as res.partner&lt;br&gt;
field: the technical field name, not the UI label&lt;br&gt;
source_type: string, integer, decimal, or date&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Compare the Spec with the Live Schema&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ERP software consultants check calls fields_get once per model and flags missing fields, read-only targets, and type mismatches.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import csv&lt;br&gt;
import xmlrpc.client&lt;/p&gt;

&lt;p&gt;URL, DB, USER, KEY = "&lt;a href="https://erp-sandbox.example.com" rel="noopener noreferrer"&gt;https://erp-sandbox.example.com&lt;/a&gt;", "sandbox", "&lt;a href="mailto:audit@example.com"&gt;audit@example.com&lt;/a&gt;", "API_KEY"&lt;br&gt;
uid = xmlrpc.client.ServerProxy(f"{URL}/xmlrpc/2/common").authenticate(DB, USER, KEY, {})  # Why: API keys avoid stored passwords&lt;br&gt;
models = xmlrpc.client.ServerProxy(f"{URL}/xmlrpc/2/object")&lt;/p&gt;

&lt;h1&gt;
  
  
  Odoo field types that can accept each spec type
&lt;/h1&gt;

&lt;p&gt;COMPAT = {"string": {"char", "text", "selection"}, "integer": {"integer", "many2one"},&lt;br&gt;
          "decimal": {"float", "monetary"}, "date": {"date", "datetime"}}&lt;/p&gt;

&lt;p&gt;def live_schema(model):&lt;br&gt;
    # Why: fields_get returns the real schema, including custom fields added after install&lt;br&gt;
    return models.execute_kw(DB, uid, KEY, model, "fields_get", [],&lt;br&gt;
                             {"attributes": ["type", "required", "readonly"]})&lt;/p&gt;

&lt;p&gt;def audit(rows):&lt;br&gt;
    problems, schemas = [], {}&lt;br&gt;
    for r in rows:&lt;br&gt;
        m, name = r["model"], r["field"]&lt;br&gt;
        schemas.setdefault(m, live_schema(m))  # Why: one API call per model, not per row&lt;br&gt;
        spec = schemas[m].get(name)&lt;br&gt;
        if spec is None:&lt;br&gt;
            problems.append(f"MISSING   {m}.{name}")&lt;br&gt;
        elif spec["readonly"]:  # Why: read-only usually means computed, so loading it needs a design call&lt;br&gt;
            problems.append(f"READONLY  {m}.{name}")&lt;br&gt;
        elif spec["type"] not in COMPAT[r["source_type"]]:&lt;br&gt;
            problems.append(f"TYPE      {m}.{name}: {r['source_type']} vs {spec['type']}")&lt;br&gt;
    return problems, schemas&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Cover Required Fields and Gate the Build&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Spreadsheets hide missing required fields best, so check in reverse: start from the schema.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def unmapped_required(rows, schemas):&lt;br&gt;
    mapped = {(r["model"], r["field"]) for r in rows}&lt;br&gt;
    gaps = []&lt;br&gt;
    for model, schema in schemas.items():&lt;br&gt;
        required = [n for n, s in schema.items() if s["required"] and not s["readonly"]]&lt;br&gt;
        defaults = models.execute_kw(DB, uid, KEY, model, "default_get", [required])&lt;br&gt;
        # Why: a field with a default value does not need a mapping row&lt;br&gt;
        gaps += [f"UNMAPPED  {model}.{n}" for n in required&lt;br&gt;
                 if n not in defaults and (model, n) not in mapped]&lt;br&gt;
    return gaps&lt;/p&gt;

&lt;p&gt;rows = list(csv.DictReader(open("mapping.csv")))&lt;br&gt;
problems, schemas = audit(rows)&lt;br&gt;
problems += unmapped_required(rows, schemas)&lt;br&gt;
print("\n".join(problems) or "mapping OK")&lt;br&gt;
raise SystemExit(1 if problems else 0)  # Why: a non-zero exit fails the CI job&lt;/p&gt;

&lt;p&gt;Trade-offs: this check is structural and cannot validate values or relations. A dry-run import on seeded data catches those, but it needs fixtures and runs slower. Run the structural check on every spec change and nightly, because a new custom module can invalidate an approved spec.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our ERP projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a Shanghai-based logistics provider needed a single open-source ERP for inventory, order processing, and real-time tracking.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Call fields_get once per model and cache it to keep API calls low.&lt;br&gt;
Map technical field names, never UI labels.&lt;br&gt;
Audit both directions: spec to schema for typos, schema to spec for unmapped required fields.&lt;br&gt;
Exit non-zero on any finding so the pipeline, not a reviewer, blocks a bad spec.&lt;/p&gt;

&lt;p&gt;Questions about adapting this to another ERP? Drop them in the comments, or reach out to &lt;a href="//oodles.com/contact-us"&gt;ERP software consultants&lt;/a&gt; at Oodles for a deeper review.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What do ERP software consultants deliver that developers should verify?&lt;/strong&gt;&lt;br&gt;
ERP software consultants typically deliver requirement documents, process maps, and field mapping sheets. Verify the mapping sheet first, because every migration job reads it. Parse it as CSV and compare it with the live schema before any build starts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I get field metadata from Odoo?&lt;/strong&gt;&lt;br&gt;
Call fields_get on a model through XML-RPC or JSON-RPC. It returns each field's type, required flag, relation, and readonly status. Pass an attributes list to limit the payload, and cache results per model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does this work on ERPs other than Odoo?&lt;/strong&gt;&lt;br&gt;
The pattern works wherever the platform exposes schema metadata through an API. Dynamics 365 and Business Central publish OData $metadata. Only the schema-fetch function changes; the comparison logic stays the same across platforms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can a structural check replace a test migration?&lt;/strong&gt;&lt;br&gt;
No. A structural check catches missing fields, type mismatches, and unmapped required fields, but not bad values, duplicates, or broken relations. Pair it with a dry-run import on seeded data before cutover.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How often should I rerun the mapping audit?&lt;/strong&gt;&lt;br&gt;
Run it on every change to the mapping file and nightly against the sandbox. Nightly runs catch schema drift from new custom modules or upgrades, which can invalidate an approved spec.&lt;/p&gt;

</description>
      <category>erp</category>
      <category>consultation</category>
      <category>ai</category>
      <category>productivity</category>
    </item>
    <item>
      <title>CRM Customization Services: Building Idempotent Sync in Node.js</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Tue, 24 Nov 2026 05:36:02 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/crm-customization-services-building-idempotent-sync-in-nodejs-26l3</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/crm-customization-services-building-idempotent-sync-in-nodejs-26l3</guid>
      <description>&lt;p&gt;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 &lt;a href="https://www.oodles.com/crm-applications/video/client-project-spotlight:-oodles'-custom-erp-for-scalable-media-ops-and-global-content-delivery?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_56" rel="noopener noreferrer"&gt;how CRM customization services handle cross-system events in a live media platform&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building Reliable Sync for CRM Customization Services&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The design has three parts: verify and record the event, acknowledge fast, and process asynchronously with a retry limit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Record the Event Before Doing Any Work&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

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

&lt;p&gt;Return a 2xx as soon as the event is stored. Slow responses are what trigger the CRM retries in the first place.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import crypto from 'node:crypto';&lt;br&gt;
import express from 'express';&lt;/p&gt;

&lt;p&gt;const app = express();&lt;/p&gt;

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

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

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

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

&lt;p&gt;The worker then claims rows safely and passes the event ID to the ERP as its own idempotency key.&lt;/p&gt;

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

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

&lt;p&gt;Note that the claim and the updates should share one transaction in production. We trimmed that here for length.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Trade-Offs in CRM Customization Services&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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 &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, work orders, billing, and CRM data had to move between QuickBooks, Infusionsoft, and Authorize.Net without duplicates. &lt;/p&gt;

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

&lt;p&gt;Have a retry or ordering edge case that this pattern does not cover? Share it in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;CRM customization services&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are CRM customization services in a developer context?&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does idempotent mean for a webhook handler?&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do CRMs send duplicate webhooks?&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use a queue or a database table for sync events?&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How many retries should a sync worker attempt?&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

</description>
      <category>crm</category>
      <category>ai</category>
      <category>sales</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to Build Idempotent ERP Integration Services in Node.js</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Thu, 19 Nov 2026 10:05:38 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-idempotent-erp-integration-services-in-nodejs-2bnm</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-idempotent-erp-integration-services-in-nodejs-2bnm</guid>
      <description>&lt;p&gt;A customer order syncs to the ERP, the HTTP call times out at 10 seconds, and your worker retries. The ERP had already created the order. Now finance sees two invoices for one purchase. This duplicate-write failure is the most common defect we see in ERP integration services, and it appears wherever a webhook, queue, or cron job can deliver the same message twice. This guide shows &lt;a href="https://www.oodles.com/erp-integration-services/4344175?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_53" rel="noopener noreferrer"&gt;how ERP integration services handle retries safely&lt;/a&gt; with an idempotency table, classified errors, and a dead-letter state in Node.js and PostgreSQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Idempotency means that processing the same message many times produces the same result as processing it once. Without it, at-least-once delivery, which every queue and webhook provider uses, turns into duplicate records.&lt;/p&gt;

&lt;p&gt;The scenario: a Node.js 20 worker reads order events from your storefront and posts them to an ERP REST API. You need PostgreSQL 14 or later, the pg package, and an ERP endpoint that accepts JSON. The problem is widespread because systems rarely share a single delivery guarantee. The Salesforce MuleSoft Connectivity Benchmark Report (2026) found that the average organization runs 957 applications and integrates only 27 percent of them. Each unintegrated gap tends to get a quick script, and quick scripts rarely dedupe.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building Idempotent ERP Integration Services&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The pattern has three parts: a deterministic key, an atomic claim, and a classified retry loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Derive a Deterministic Key and Claim It&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A key built from the source system, entity ID, and entity version means a replay always produces the same key. We store it in a table with a primary key, so the database decides who sends.&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
CREATE TABLE sync_log (&lt;br&gt;
  idem_key   text PRIMARY KEY,           -- Why: uniqueness is enforced by the database, not app code&lt;br&gt;
  payload    jsonb NOT NULL,&lt;br&gt;
  status     text NOT NULL DEFAULT 'pending', -- pending | sent | dead&lt;br&gt;
  attempts   int  NOT NULL DEFAULT 0,&lt;br&gt;
  last_error text,&lt;br&gt;
  created_at timestamptz NOT NULL DEFAULT now()&lt;br&gt;
);&lt;br&gt;
js&lt;br&gt;
import pg from "pg";&lt;br&gt;
import { createHash } from "node:crypto";&lt;br&gt;
const pool = new pg.Pool();&lt;/p&gt;

&lt;p&gt;// Why: same order and same version always give the same key, so replays collapse into one row&lt;br&gt;
export const syncKey = (source, id, version) =&amp;gt;&lt;br&gt;
  createHash("sha256").update(&lt;code&gt;${source}:${id}:${version}&lt;/code&gt;).digest("hex");&lt;/p&gt;

&lt;p&gt;export async function claim(key, payload) {&lt;br&gt;
  const { rowCount } = await pool.query(&lt;br&gt;
    &lt;code&gt;INSERT INTO sync_log (idem_key, payload) VALUES ($1, $2)&lt;br&gt;
     ON CONFLICT (idem_key) DO NOTHING&lt;/code&gt;, // Why: atomic under concurrent workers&lt;br&gt;
    [key, payload]&lt;br&gt;
  );&lt;br&gt;
  return rowCount === 1; // true means this worker owns the send&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Step 2: Send with Classified Retries&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Retrying everything wastes time and hammers a struggling ERP. Retry only failures that can succeed later: timeouts, network errors, HTTP 429, and 5xx. Send anything else to the dead state for a human.&lt;/p&gt;

&lt;p&gt;Post the payload with the key in an Idempotency-Key header.&lt;br&gt;
On 2xx, mark the row sent.&lt;br&gt;
On other 4xx, mark it dead with the response body.&lt;br&gt;
On timeout, 429, or 5xx, wait with exponential backoff and retry.&lt;br&gt;
js&lt;br&gt;
async function mark(key, status, err = null) {&lt;br&gt;
  await pool.query(&lt;br&gt;
    "UPDATE sync_log SET status=$2, last_error=$3 WHERE idem_key=$1", [key, status, err]);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export async function send(key, payload, erpUrl, token) {&lt;br&gt;
  for (let attempt = 0; attempt &amp;lt; 5; attempt++) {&lt;br&gt;
    try {&lt;br&gt;
      const res = await fetch(erpUrl, {&lt;br&gt;
        method: "POST",&lt;br&gt;
        headers: { "Content-Type": "application/json",&lt;br&gt;
                   Authorization: &lt;code&gt;Bearer ${token}&lt;/code&gt;,&lt;br&gt;
                   "Idempotency-Key": key },   // Why: lets the ERP dedupe if it supports it&lt;br&gt;
        body: JSON.stringify(payload),&lt;br&gt;
        signal: AbortSignal.timeout(10_000),    // Why: a hung socket must not hold the worker&lt;br&gt;
      });&lt;br&gt;
      if (res.ok) return mark(key, "sent");&lt;br&gt;
      // Why: a validation error will fail identically on every retry&lt;br&gt;
      if (res.status &amp;lt; 500 &amp;amp;&amp;amp; res.status !== 429) return mark(key, "dead", await res.text());&lt;br&gt;
    } catch { /* timeout or network error: the ERP may have processed it, so retry with the same key &lt;em&gt;/ }&lt;br&gt;
    await pool.query("UPDATE sync_log SET attempts=$2 WHERE idem_key=$1", [key, attempt + 1]);&lt;br&gt;
    await new Promise(r =&amp;gt; setTimeout(r, 2 *&lt;/em&gt; attempt * 500)); // Why: backoff protects the ERP&lt;br&gt;
  }&lt;br&gt;
  return mark(key, "dead", "retries exhausted");&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Step 3: Weigh the Trade-Offs in ERP Integration Services&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A database table beats Redis SETNX for this job because the claim and the audit trail live in one transactional place. Redis is faster, but a key expiry or restart can silently reopen the window for duplicates.&lt;/p&gt;

&lt;p&gt;The table has one gap. A worker that crashes after claim leaves a pending row that no replay will resend. Run a sweeper that retries rows stuck in pending for more than a few minutes. If your ERP honors Idempotency-Key natively, keep the table anyway, since it also gives you the dead-letter queue and a reconciliation report.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our ERP integration services projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, system and ERP, for example a storefront syncing orders to an ERP over REST produced duplicate records after timeouts. We added an idempotency table, error classification, and a pending sweeper. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Build the idempotency key from source, entity ID, and version so replays always collide.&lt;br&gt;
Let a database primary key decide ownership of a send, not application checks.&lt;br&gt;
Treat a timeout as unknown, not failed, and always retry with the same key.&lt;br&gt;
Send non-retryable 4xx responses to a dead state instead of looping.&lt;br&gt;
Sweep stale pending rows, or crashed workers will lose messages quietly.&lt;/p&gt;

&lt;p&gt;Questions about your own sync design? Share them in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;ERP integration services&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are ERP integration services?&lt;/strong&gt;&lt;br&gt;
ERP integration services connect an ERP system to other applications such as storefronts, CRMs, and warehouse tools. They include data mapping, API or middleware development, synchronization, error handling, testing, and monitoring so records stay consistent across systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do ERP syncs create duplicate records?&lt;/strong&gt;&lt;br&gt;
Queues, webhooks, and retry loops deliver at least once, not exactly once. If a request times out after the ERP already processed it, the retry creates a second record unless the sender attaches a stable idempotency key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should a timeout be retried?&lt;/strong&gt;&lt;br&gt;
Yes, but only with the same idempotency key. A timeout means the outcome is unknown, since the ERP may have committed the write. Reusing the key lets the database or ERP reject the duplicate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Which HTTP errors should not be retried?&lt;/strong&gt;&lt;br&gt;
Most 4xx responses, such as 400 and 422, indicate invalid data that will fail identically each time. Retry only 429, 5xx, timeouts, and network errors. Route the rest to a dead-letter state for review.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is a database table better than Redis for idempotency?&lt;/strong&gt;&lt;br&gt;
For ERP syncs, usually yes. A PostgreSQL primary key gives an atomic claim, durable storage, and an audit trail together. Redis is faster but loses guarantees if keys expire or the instance restarts.&lt;/p&gt;

</description>
      <category>erp</category>
      <category>api</category>
      <category>ai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to Build a Resumable Salesforce CDC Consumer in Node.js</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Tue, 17 Nov 2026 09:46:13 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-a-resumable-salesforce-cdc-consumer-in-nodejs-5ecf</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-build-a-resumable-salesforce-cdc-consumer-in-nodejs-5ecf</guid>
      <description>&lt;p&gt;A Change Data Capture (CDC) consumer that restarts from the wrong position either drops Opportunity updates or replays three days of them. This failure shows up after every deploy, crash, or network drop in services that mirror Salesforce records into a database. The fix is a durable checkpoint. If you want background on &lt;a href="https://www.oodles.com/salesforce?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_52" rel="noopener noreferrer"&gt;how Salesforce change events work in production, read that overview first&lt;/a&gt;. This article then shows how to store replay IDs, resume a gRPC subscription, and make replays harmless, using Node.js, the Pub/Sub API, and Postgres.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You need a stream with a durable position, and CDC provides one through the replay ID. The scenario: a worker subscribes to /data/OpportunityChangeEvent and mirrors each change into Postgres for reporting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;CDC enabled for Opportunity in Setup.&lt;br&gt;
An OAuth access token, instance URL, and org ID.&lt;br&gt;
pubsub_api.proto from the forcedotcom/pub-sub-api repository.&lt;br&gt;
@grpc/grpc-js, @grpc/proto-loader, avsc, and pg.&lt;/p&gt;

&lt;p&gt;The time limit matters. The Streaming API documentation on message durability states that events are retained for 72 hours and that events outside the window are discarded. A Salesforce help article (2026) adds that CometD clients can end up with an invalid replay ID after events age out, and it recommends the Pub/Sub API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building a Salesforce CDC Consumer with Replay Checkpoints&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The consumer needs three parts: a checkpoint table, a resumable subscription, and an idempotent apply step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Store the checkpoint beside the data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Keep the replay ID in the same database as the mirrored rows, so one transaction covers both. their calls replay IDs opaque, so store them as bytes.&lt;/p&gt;

&lt;p&gt;Create one checkpoint row per channel.&lt;br&gt;
Create a table of applied change keys.&lt;br&gt;
sql&lt;br&gt;
-- Why: the checkpoint lives next to the data it describes&lt;br&gt;
CREATE TABLE cdc_checkpoint (channel text PRIMARY KEY, replay_id bytea NOT NULL);&lt;br&gt;
-- Why: a replayed event hits this key and becomes a no-op&lt;br&gt;
CREATE TABLE cdc_applied (tx_key text, seq int, PRIMARY KEY (tx_key, seq));&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Subscribe from the saved position&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Resume with the CUSTOM replay preset and the stored bytes. Use LATEST only on the very first run.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
const grpc = require('@grpc/grpc-js');&lt;br&gt;
const loader = require('@grpc/proto-loader');&lt;br&gt;
const def = loader.loadSync('pubsub_api.proto', { keepCase: true, longs: String, enums: String, defaults: true });&lt;br&gt;
const { PubSub } = grpc.loadPackageDefinition(def).eventbus.v1;&lt;/p&gt;

&lt;p&gt;function subscribe(auth, channel, saved, onBatch) {&lt;br&gt;
  const client = new PubSub('api.pubsub.salesforce.com:7443', grpc.credentials.createSsl());&lt;br&gt;
  const meta = new grpc.Metadata();&lt;br&gt;
  meta.add('accesstoken', auth.token);&lt;br&gt;
  meta.add('instanceurl', auth.instanceUrl);&lt;br&gt;
  meta.add('tenantid', auth.orgId);&lt;br&gt;
  const call = client.Subscribe(meta);&lt;br&gt;
  const N = 50; // Why: caps in-flight events so memory stays flat&lt;br&gt;
  const start = saved ? { replay_preset: 'CUSTOM', replay_id: saved } : { replay_preset: 'LATEST' };&lt;br&gt;
  call.write({ topic_name: channel, num_requested: N, ...start });&lt;br&gt;
  call.on('data', async (res) =&amp;gt; {&lt;br&gt;
    call.pause(); // Why: keeps batches in order while we await the database&lt;br&gt;
    await onBatch(client, meta, res.events, res.latest_replay_id);&lt;br&gt;
    call.resume();&lt;br&gt;
    // Why: the server stops sending once the requested count is used up&lt;br&gt;
    if (res.pending_num_requested === 0) call.write({ topic_name: channel, num_requested: N });&lt;br&gt;
  });&lt;br&gt;
  return call;&lt;br&gt;
}&lt;br&gt;
Step 3: Apply changes idempotently and checkpoint atomically&lt;/p&gt;

&lt;p&gt;At-least-once delivery plus a dedupe key is simpler than chasing exactly-once. The trade-off is one extra table, which you prune after 72 hours because nothing older can replay.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
const avro = require('avsc');&lt;br&gt;
const types = new Map(); // Why: schemas rarely change, so fetch each ID once&lt;/p&gt;

&lt;p&gt;async function onBatch(client, meta, events, latest) {&lt;br&gt;
  const db = await pool.connect(); // pool is a pg.Pool created at startup&lt;br&gt;
  try {&lt;br&gt;
    await db.query('BEGIN');&lt;br&gt;
    for (const ev of events) {&lt;br&gt;
      let type = types.get(ev.event.schema_id);&lt;br&gt;
      if (!type) {&lt;br&gt;
        const s = await new Promise((ok, no) =&amp;gt;&lt;br&gt;
          client.GetSchema({ schema_id: ev.event.schema_id }, meta, (e, r) =&amp;gt; (e ? no(e) : ok(r)))&lt;br&gt;
        );&lt;br&gt;
        type = avro.Type.forSchema(JSON.parse(s.schema_json));&lt;br&gt;
        types.set(ev.event.schema_id, type);&lt;br&gt;
      }&lt;br&gt;
      const rec = type.fromBuffer(ev.event.payload); // Avro bytes to object&lt;br&gt;
      const h = rec.ChangeEventHeader;&lt;br&gt;
      const fresh = await db.query(&lt;br&gt;
        'INSERT INTO cdc_applied VALUES ($1,$2) ON CONFLICT DO NOTHING', [h.transactionKey, h.sequenceNumber]);&lt;br&gt;
      if (fresh.rowCount === 1) await applyChange(db, h, rec); // your upsert logic&lt;br&gt;
    }&lt;br&gt;
    // Why: runs even for empty keep-alive replies, so quiet channels never age out&lt;br&gt;
    await db.query(&lt;br&gt;
      'INSERT INTO cdc_checkpoint VALUES ($1,$2) ON CONFLICT (channel) DO UPDATE SET replay_id = EXCLUDED.replay_id',&lt;br&gt;
      [CHANNEL, latest]);&lt;br&gt;
    await db.query('COMMIT'); // Why: data and checkpoint succeed or fail together&lt;br&gt;
  } catch (e) { await db.query('ROLLBACK'); throw e; } finally { db.release(); }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Against the older CometD route, this costs you gRPC setup and Avro decoding. In return, It's documents replay tightening for the Pub/Sub API, which advances your replay ID past irrelevant events on reconnect.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Crm projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a client from real estate mirrored Opportunities into Postgres through a CometD listener. Each deploy left gaps, so a nightly reconciliation job ran to repair them. We moved the listener to the Pub/Sub API with the checkpoint design above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Write the replay ID in the same transaction as the data, or a crash will split them.&lt;br&gt;
Treat replay IDs as opaque bytes, never as numbers you can increment.&lt;br&gt;
Persist the latest replay ID on empty replies to stay inside the 72-hour window.&lt;br&gt;
Dedupe on transactionKey and sequenceNumber so replays do no harm.&lt;br&gt;
Pause the stream while awaiting the database to keep event order.&lt;/p&gt;

&lt;p&gt;Have a replay edge case or a gap you could not explain? Share it in the comments, or send your &lt;a href="//oodles.com/contact-us"&gt;Salesforce&lt;/a&gt; architecture questions to our team directly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Salesforce Change Data Capture?&lt;/strong&gt;&lt;br&gt;
It publishes a change event whenever a record is created, updated, deleted, or undeleted. Subscribers receive field values and a header describing the change, which lets external systems stay in sync without polling the API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How long are change events stored?&lt;/strong&gt;&lt;br&gt;
It retains change events for 72 hours. Events older than that are purged, and Salesforce does not guarantee storage beyond the window. A consumer that stays offline longer must rebuild its state from a full data export.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use CometD or the Pub/Sub API?&lt;/strong&gt;&lt;br&gt;
Choose the Pub/Sub API for new work. It uses gRPC, supports flow control, and adds replay tightening. It recommends migrating CometD subscribers, which can see long silent periods or invalid replay IDs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What do the replay options mean?&lt;/strong&gt;&lt;br&gt;
LATEST delivers only new events, matching CometD’s -1. EARLIEST returns everything in the retention window, matching -2. CUSTOM resumes after a saved replay ID, which is the right choice after a restart.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I avoid processing an event twice?&lt;/strong&gt;&lt;br&gt;
Assume at-least-once delivery. Store the transactionKey and sequenceNumber from the change header with a unique constraint, and skip the write when the insert conflicts. Prune those keys after 72 hours.&lt;/p&gt;

</description>
      <category>salesforce</category>
      <category>crm</category>
    </item>
    <item>
      <title>How to Stop OAuth Token Stampedes in Zoho Integration Services (Python and Redis)</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Mon, 16 Nov 2026 07:15:25 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-stop-oauth-token-stampedes-in-zoho-integration-services-python-and-redis-25i0</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-stop-oauth-token-stampedes-in-zoho-integration-services-python-and-redis-25i0</guid>
      <description>&lt;p&gt;Eight workers share one Zoho refresh token. At minute 60 the cached access token expires, every worker gets a 401, and all eight request a new token at once. Retries pile on, Zoho throttles the refresh endpoint, and the queue stalls. This pattern shows up in order-sync and lead-sync jobs, and it is the first thing we check when we review &lt;a href="https://www.oodles.com/zoho/7144783?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_51" rel="noopener noreferrer"&gt;how Zoho Integration Services work in production&lt;/a&gt;. Below, we build a single-flight token refresh in Python with Redis so that exactly one worker refreshes while the rest wait.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Scenario: several Python workers (Celery, RQ, or FastAPI background tasks) push ERP or storefront data into Zoho CRM through the REST API, all using one OAuth client and one refresh token.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Python 3.10+, requests, and redis-py&lt;br&gt;
Redis 6+ reachable from every worker&lt;br&gt;
A Zoho refresh token with the scopes your calls need&lt;br&gt;
The accounts URL for your data center&lt;/p&gt;

&lt;p&gt;The accounts URL matters because the accounts server URL is specific to the data center where the user is located. Using accounts.zoho.com against an Indian or European org fails. &lt;/p&gt;

&lt;p&gt;The limits are the real constraint. An access token is valid for one hour. A refresh token can create up to ten access tokens in ten minutes, and creation is blocked for the rest of that window once the limit is hit. Eight workers retrying a failed refresh burn through ten tokens in seconds. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building Token-Safe Zoho Integration Services with Single-Flight Refresh&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Single-flight means concurrent callers share one in-progress operation instead of each starting their own. The three steps below apply it to token refresh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Share One Token Across Zoho Integration Services Workers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Per-process token caches are the root cause, because each process refreshes on its own clock. Store the token in Redis with a TTL set slightly below Zoho’s expiry. Every worker then reads the same value, and Redis evicts it before it can go stale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The flow each worker follows:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Read the token from Redis.&lt;br&gt;
On a hit, call Zoho.&lt;br&gt;
On a miss, try to take the refresh lock.&lt;br&gt;
Lock winner refreshes and writes the token. Everyone else polls Redis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Add a Lock So Only One Worker Refreshes&lt;/strong&gt;&lt;br&gt;
python&lt;br&gt;
import time&lt;br&gt;
import uuid&lt;br&gt;
import redis&lt;br&gt;
import requests&lt;/p&gt;

&lt;p&gt;r = redis.Redis(decode_responses=True)&lt;/p&gt;

&lt;p&gt;ACCOUNTS = "&lt;a href="https://accounts.zoho.com" rel="noopener noreferrer"&gt;https://accounts.zoho.com&lt;/a&gt;"  # Why: must match your org's data center (.eu, .in, ...)&lt;br&gt;
TOKEN_KEY, LOCK_KEY = "zoho:access_token", "zoho:refresh_lock"&lt;br&gt;
SAFETY_MARGIN = 300  # Why: expire our copy 5 min early so no worker sends a dying token&lt;/p&gt;

&lt;h1&gt;
  
  
  Why: delete the lock only if we still own it (avoids freeing another worker's lock)
&lt;/h1&gt;

&lt;p&gt;RELEASE = """&lt;br&gt;
if redis.call('get', KEYS[1]) == ARGV[1] then&lt;br&gt;
  return redis.call('del', KEYS[1])&lt;br&gt;
end&lt;br&gt;
return 0&lt;br&gt;
"""&lt;/p&gt;

&lt;p&gt;def _refresh(cfg):&lt;br&gt;
    resp = requests.post(f"{ACCOUNTS}/oauth/v2/token", data={&lt;br&gt;
        "grant_type": "refresh_token",&lt;br&gt;
        "client_id": cfg["client_id"],&lt;br&gt;
        "client_secret": cfg["client_secret"],&lt;br&gt;
        "refresh_token": cfg["refresh_token"],&lt;br&gt;
    }, timeout=10)&lt;br&gt;
    body = resp.json()&lt;br&gt;
    if "access_token" not in body:&lt;br&gt;
        raise RuntimeError(f"Zoho refresh failed: {body}")  # Why: fail loudly, never retry in a tight loop&lt;br&gt;
    r.set(TOKEN_KEY, body["access_token"], ex=body["expires_in"] - SAFETY_MARGIN)&lt;br&gt;
    return body["access_token"]&lt;/p&gt;

&lt;p&gt;def get_token(cfg, wait=10):&lt;br&gt;
    deadline = time.time() + wait&lt;br&gt;
    while time.time() &amp;lt; deadline:&lt;br&gt;
        token = r.get(TOKEN_KEY)&lt;br&gt;
        if token:&lt;br&gt;
            return token&lt;br&gt;
        owner = str(uuid.uuid4())&lt;br&gt;
        # Why: SET NX is atomic, so exactly one worker wins under high concurrency&lt;br&gt;
        if r.set(LOCK_KEY, owner, nx=True, ex=15):&lt;br&gt;
            try:&lt;br&gt;
                return _refresh(cfg)&lt;br&gt;
            finally:&lt;br&gt;
                r.eval(RELEASE, 1, LOCK_KEY, owner)&lt;br&gt;
        time.sleep(0.2)  # Why: losers poll the cache instead of hitting Zoho&lt;br&gt;
    raise TimeoutError("No Zoho token available within wait window")&lt;br&gt;
Step 3: Retry Once on 401 and Weigh the Trade-offs&lt;/p&gt;

&lt;p&gt;A token can still die early if someone revokes it or the clock drifts. Handle that with one bounded retry.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def zoho_get(cfg, path, **params):&lt;br&gt;
    for _ in range(2):  # Why: one retry only, so a bad scope cannot loop forever&lt;br&gt;
        token = get_token(cfg)&lt;br&gt;
        resp = requests.get(&lt;br&gt;
            f"{cfg['api_domain']}{path}", params=params, timeout=15,&lt;br&gt;
            headers={"Authorization": f"Zoho-oauthtoken {token}"},&lt;br&gt;
        )&lt;br&gt;
        if resp.status_code != 401:&lt;br&gt;
            resp.raise_for_status()&lt;br&gt;
            return resp.json() if resp.content else {}  # Why: Zoho returns 204 for empty searches&lt;br&gt;
        # Why: evict only if the cache still holds the rejected token,&lt;br&gt;
        # otherwise we would delete a fresh token another worker just wrote&lt;br&gt;
        if r.get(TOKEN_KEY) == token:&lt;br&gt;
            r.delete(TOKEN_KEY)&lt;br&gt;
    raise RuntimeError("Zoho rejected a fresh token; check scopes or revocation")&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trade-offs we weighed:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Redis lock vs. per-process refresh: the lock adds one dependency but removes the burst entirely.&lt;br&gt;
Refresh on 401 vs. scheduled refresh: a scheduled job needs its own failure handling. Refresh-on-miss with a safety margin needs none.&lt;br&gt;
Database row lock vs. Redis: a database works, but you must write TTL cleanup yourself.&lt;br&gt;
Lock TTL: 15 seconds covers a slow accounts server. A shorter TTL risks two refreshes, and a longer one stalls workers if the winner crashes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Zoho Integration services projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a Celery worker pool syncing ERP orders into Zoho CRM suffered refresh bursts at token expiry that triggered Access Denied and left a stated number of jobs failing. We moved token storage to Redis with a single-flight lock and a bounded 401 retry.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Zoho issues at most ten access tokens per refresh token every ten minutes, so per-worker caches fail under concurrency.&lt;br&gt;
Store one token in Redis with a TTL below Zoho’s one-hour expiry.&lt;br&gt;
Use an atomic SET NX lock so one worker refreshes and the others poll the cache.&lt;br&gt;
On a 401, evict the cached token only if it still matches the rejected one.&lt;br&gt;
Retry once, then fail with a clear error, so scope and revocation problems surface fast.&lt;/p&gt;

&lt;p&gt;Have a different Zoho failure mode, such as webhook channel expiry or bulk write errors? Drop it in the comments, or reach out about Z&lt;a href="//oodles.com/contact-us"&gt;oho Integration services&lt;/a&gt; for your stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How long is a Zoho access token valid?&lt;/strong&gt;&lt;br&gt;
In Zoho Integration Services an access token is valid for one hour (3600 seconds). Refresh tokens do not expire until a user revokes them. Cache the access token centrally and renew it shortly before expiry instead of on every call. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How many access tokens can one refresh token generate?&lt;/strong&gt;&lt;br&gt;
Up to ten in a ten-minute span, after which creation is blocked for the rest of the window. In multi-worker deployments, share one cached token so refreshes stay far below that ceiling. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does Zoho return “Access Denied” or “invalid_code”?&lt;/strong&gt;&lt;br&gt;
In Zoho Integration Services Access Denied usually means you hit the token throttle. An invalid_code error appears when you generate an access token from a revoked refresh token. Also confirm your accounts URL matches the org’s data center. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do Zoho Integration services need region-specific URLs?&lt;/strong&gt;&lt;br&gt;
In Zoho Integration Services Yes. Both the accounts server and the API domain depend on the org’s data center. Read api_domain from the token response rather than hardcoding it, and keep the accounts URL in configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use Redis or a database for the token cache?&lt;/strong&gt;&lt;br&gt;
Redis fits best because TTL expiry and atomic SET NX locking come built in. A database works if you add row locking and cleanup. Either way, only one refresh should run at a time.&lt;/p&gt;

</description>
      <category>zoho</category>
      <category>zohocrm</category>
      <category>deluge</category>
      <category>crm</category>
    </item>
    <item>
      <title>Odoo Development Services: Fixing N+1 Queries in Computed Fields</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Fri, 13 Nov 2026 09:13:12 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/odoo-development-services-fixing-n1-queries-in-computed-fields-956</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/odoo-development-services-fixing-n1-queries-in-computed-fields-956</guid>
      <description>&lt;p&gt;A computed field that calls search_count once per record behaves in a demo database and stalls in production. The query count grows with the row count, so a list view of 5,000 partners fires 5,000 extra queries. This N+1 pattern appears wherever Odoo development services add per-record aggregates to standard models, such as shipment counts, open balances, or overdue totals. This article shows how to find the pattern with the built-in profiler and replace it with one grouped query. It targets Odoo 17 and later on PostgreSQL, and every snippet lives in a custom module. For wider context, see &lt;a href="https://www.oodles.com/odoo-implementation/video/ecom-express?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_51" rel="noopener noreferrer"&gt;how Odoo development services handle logistics workloads&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Odoo Development Services The N+1 problem means one query loads N records, then N more queries read something about each one. Cybrosys’s Odoo ORM performance guide calls it one of the most common causes of Odoo performance problems. Odoo softens it with prefetching. The Odoo 17 source (odoo/models.py) sets PREFETCH_MAX to 1000 records per prefetch batch and INSERT_BATCH_SIZE to 100 for batch creates. Prefetch only batches field reads, though. It cannot batch a search_count() that you wrote inside a loop.&lt;/p&gt;

&lt;p&gt;Our scenario is a custom logistics_shipment module. It defines a logistics.shipment model with a partner_id many2one, and a shipment_count field on res.partner that a list view displays. You need Odoo 17 or later, developer mode, and realistic data volume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Odoo Development Services Fix: One Grouped Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The fix is one GROUP BY that counts every partner’s shipments, with results handed back to the recordset.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Measure before changing anything&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Profile first, because guessing the slow field is unreliable. The built-in profiler ships with Odoo 16 and later.&lt;/p&gt;

&lt;p&gt;Activate developer mode.&lt;br&gt;
Enable profiling from the developer tools menu.&lt;br&gt;
Open the partner list view once.&lt;br&gt;
Read the profiler output and look for the same SQL repeated with a different partner_id each time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Group in the database&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is the slow version most modules start with.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from odoo import api, fields, models&lt;/p&gt;

&lt;p&gt;class ResPartner(models.Model):&lt;br&gt;
    _inherit = "res.partner"  # Why: extend the model, never edit core code&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;shipment_ids = fields.One2many("logistics.shipment", "partner_id")
shipment_count = fields.Integer(compute="_compute_shipment_count")

@api.depends("shipment_ids")
def _compute_shipment_count(self):
    for partner in self:
        # Slow: one COUNT query per partner, so N+1 under a list view
        partner.shipment_count = self.env["logistics.shipment"].search_count(
            [("partner_id", "=", partner.id)]
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Replace the loop body with a grouped read.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
    @api.depends("shipment_ids")&lt;br&gt;
    def &lt;em&gt;compute_shipment_count(self):&lt;br&gt;
        # Why: one GROUP BY query covers the whole recordset&lt;br&gt;
        groups = self.env["logistics.shipment"]._read_group(&lt;br&gt;
            domain=[("partner_id", "in", self.ids)],&lt;br&gt;
            groupby=["partner_id"],&lt;br&gt;
            aggregates=["&lt;/em&gt;_count"],&lt;br&gt;
        )&lt;br&gt;
        counts = {partner.id: count for partner, count in groups}&lt;br&gt;
        for partner in self:&lt;br&gt;
            # Why: partners without shipments are absent from the result, so default to 0&lt;br&gt;
            partner.shipment_count = counts.get(partner.id, 0)&lt;/p&gt;

&lt;p&gt;Also set index=True on partner_id in the shipment model. The grouped query filters on that column, so the index keeps it fast as the table grows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Trade-offs for Odoo development services at scale&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Pick the option that matches how the field is used.&lt;/p&gt;

&lt;p&gt;Non-stored compute with _read_group (shown above): adds no write overhead and costs one query per read of the field. It suits fields that only appear in forms and list views.&lt;br&gt;
store=True: the value is precomputed, searchable, and groupable. Every shipment write now triggers a recompute on the partner, so writes get slower. Choose it for read-heavy dashboards.&lt;br&gt;
Raw SQL: fastest for very large aggregates, but it bypasses record rules and access rights. Use it only when profiling shows the grouped ORM read is the bottleneck.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Odoo development services projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a logistics provider’s partner and shipment lists slowed as volume grew.&lt;/p&gt;

&lt;p&gt;Key Takeaways&lt;br&gt;
Prefetching batches field reads only, so any search() or search_count() inside a loop still produces N+1 queries.&lt;br&gt;
Profile first and look for repeated identical SQL, then fix only the fields the profiler flags.&lt;br&gt;
Use _read_group with __count and a dictionary lookup to turn N queries into one.&lt;br&gt;
Choose stored fields only for read-heavy data, because they move the cost to every write.&lt;br&gt;
Index the grouping column, and treat raw SQL as a last resort because it skips record rules.&lt;br&gt;
Discuss It&lt;/p&gt;

&lt;p&gt;Hit a slow computed field in your own module? Post the profiler output in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;Odoo development services&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the N+1 query problem in Odoo?&lt;/strong&gt;&lt;br&gt;
It occurs when code runs one query to fetch N records, then one extra query per record to read related data or aggregates. Query count scales with record count, so views that look fine on small test data slow down in production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does Odoo prefetching fix N+1 queries automatically?&lt;/strong&gt;&lt;br&gt;
Only for field reads on records in the same recordset. Prefetch loads related fields in batches, but it cannot merge a search(), search_count(), or single-record browse() call that you place inside a loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use read_group or _read_group?&lt;/strong&gt;&lt;br&gt;
Use read_group() when a client consumes dictionaries, such as an RPC call. Use _read_group() inside compute methods for tuple results. Signatures changed between releases, so confirm the one in your Odoo version before copying code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I find slow computed fields in Odoo?&lt;/strong&gt;&lt;br&gt;
Enable developer mode and the built-in profiler, then load the slow view. Repeated identical SQL statements that differ only by record id point to a per-record compute or search that needs batching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When do Odoo development services need raw SQL?&lt;/strong&gt;&lt;br&gt;
Rarely. Reach for it only after profiling shows a grouped ORM read is the bottleneck, such as aggregates over millions of rows. Raw SQL bypasses record rules and access rights, so add company and security filters yourself.&lt;/p&gt;

</description>
      <category>odoo</category>
      <category>erp</category>
      <category>development</category>
      <category>python</category>
    </item>
    <item>
      <title>Fixing Salesforce Governor Limit Errors in Apex Triggers</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Thu, 12 Nov 2026 11:32:51 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/fixing-salesforce-governor-limit-errors-in-apex-triggers-1i7l</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/fixing-salesforce-governor-limit-errors-in-apex-triggers-1i7l</guid>
      <description>&lt;p&gt;A trigger passes its unit test with one record, then fails a 200-row import with System.LimitException: Too many SOQL queries: 101. &lt;a href="https://www.oodles.com/salesforce?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_50" rel="noopener noreferrer"&gt;Salesforce bulk data loads&lt;/a&gt; trigger this whenever Data Loader, Bulk API, or a scheduled integration pushes many records through code written for single-record edits. It usually surfaces in production first, because sandbox test data rarely reaches 200 rows per batch. The fix is not a retry or a bigger license. It is a change in how the trigger reads and writes data. Below, we refactor a per-record Opportunity trigger into a bulk-safe one and cover the trade-offs of each design choice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A governor limit is a per-transaction cap that the Apex runtime enforces on shared servers. Our scenario is an after update trigger on Opportunity that rolls the Amount of newly closed-won deals into a custom Total_Won__c field on the parent Account.&lt;/p&gt;

&lt;p&gt;Prerequisites: a sandbox or scratch org, a Currency field named Total_Won__c on Account, and basic Apex knowledge.&lt;/p&gt;

&lt;p&gt;The numbers explain the failure. The Apex Developer Guide sets synchronous transactions at 100 SOQL queries. It also allows 150 DML statements and 10,000 records processed by DML. Bulk loads deliver up to 200 records per trigger invocation, so one query per record fails on record 101. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bulkifying Salesforce Apex Triggers in Three Steps&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The short answer: collect IDs in the loop, query once, and write once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Find Where Salesforce Runs Queries Inside Loops&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Locate every SOQL and DML statement that sits inside a loop over Trigger.new. Follow this audit:&lt;/p&gt;

&lt;p&gt;Search the trigger and its helper classes for [SELECT and update inside loops.&lt;br&gt;
List the fields the loop actually needs.&lt;br&gt;
Note any condition that can skip records early.&lt;/p&gt;

&lt;p&gt;This is the failing version:&lt;/p&gt;

&lt;p&gt;apex&lt;br&gt;
trigger OpportunityTrigger on Opportunity (after update) {&lt;br&gt;
    for (Opportunity opp : Trigger.new) {&lt;br&gt;
        // Why this fails: one query per record, so record 101 breaks the 100 SOQL limit&lt;br&gt;
        Account acc = [SELECT Id, Total_Won_&lt;em&gt;c FROM Account WHERE Id = :opp.AccountId];&lt;br&gt;
        acc.Total_Won&lt;/em&gt;&lt;em&gt;c = (acc.Total_Won&lt;/em&gt;&lt;em&gt;c == null ? 0 : acc.Total_Won&lt;/em&gt;_c) + opp.Amount;&lt;br&gt;
        update acc; // Why this fails too: one DML per record, capped at 150 statements&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Step 2: Collect, Query Once, Write Once&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Gather the data into a Map, run one query with IN, then issue one DML statement. The map also merges several deals for the same Account.&lt;/p&gt;

&lt;p&gt;apex&lt;br&gt;
trigger OpportunityTrigger on Opportunity (after update) {&lt;br&gt;
    Map wonByAccount = new Map();&lt;br&gt;
    for (Opportunity opp : Trigger.new) {&lt;br&gt;
        // Why: act only on the stage change, so later edits do not double count&lt;br&gt;
        if (opp.StageName == 'Closed Won'&lt;br&gt;
            &amp;amp;&amp;amp; Trigger.oldMap.get(opp.Id).StageName != 'Closed Won'&lt;br&gt;
            &amp;amp;&amp;amp; opp.AccountId != null &amp;amp;&amp;amp; opp.Amount != null) {&lt;br&gt;
            Decimal running = wonByAccount.containsKey(opp.AccountId)&lt;br&gt;
                ? wonByAccount.get(opp.AccountId) : 0;&lt;br&gt;
            wonByAccount.put(opp.AccountId, running + opp.Amount);&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
    if (wonByAccount.isEmpty()) return; // Why: skip the query when nothing qualifies&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// One query for every parent Account in this chunk
List&amp;lt;Account&amp;gt; accounts = [SELECT Id, Total_Won__c FROM Account
                          WHERE Id IN :wonByAccount.keySet()];
for (Account acc : accounts) {
    acc.Total_Won__c = (acc.Total_Won__c == null ? 0 : acc.Total_Won__c)
            + wonByAccount.get(acc.Id);
}
update accounts; // One DML statement for the whole list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Then test with 200 records in a single update call, because that is the real chunk size from Data Loader.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Weigh the Trade-Offs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Bulkification fixes query counts, but it does not remove every limit. Compare these options:&lt;/p&gt;

&lt;p&gt;Trigger with a handler class. Best for testability and bulk control. The cost is more files to maintain.&lt;br&gt;
Record-triggered Flow. Faster to build for simple logic. Flows face similar per-transaction caps, so loops that query still fail. &lt;/p&gt;

&lt;p&gt;Queueable Apex for heavy follow-up work. Asynchronous transactions allow 200 SOQL queries and 60,000 ms of CPU. The cost is eventual consistency, so the Account total updates a moment later. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Salesforce projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a Realestate client loaded 1000 plus records nightly from website through Bulk API 2.0. An Opportunity trigger hit the 101 SOQL error on 10 percent of runs. We applied the map pattern above, moved it into a Queueable job, and added a 200-record test to the deployment pipeline. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Treat 200 records as normal trigger input, and write every trigger and test for that size.&lt;br&gt;
Aim for one SOQL query and one DML statement per trigger context; a per-record query is a defect.&lt;br&gt;
Maps keyed by record ID remove queries and merge duplicate parents safely.&lt;br&gt;
Flows share per-transaction limits, so moving logic out of Apex does not cure a query-in-loop design.&lt;br&gt;
Push heavy follow-up work to Queueable Apex when the business accepts slightly delayed results.&lt;/p&gt;

&lt;p&gt;Hit a different governor limit? Share the error in the comments, or send your &lt;a href="//oodels.com/contact-us"&gt;Salesforce&lt;/a&gt; architecture questions to our team.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a governor limit in Salesforce?&lt;/strong&gt;&lt;br&gt;
A governor limit is a per-transaction cap that Salesforce enforces because customers share servers. Synchronous Apex allows 100 SOQL queries, 150 DML statements, and 10,000 ms of CPU time. Exceeding one throws an exception that code cannot handle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How many records does a trigger process at once?&lt;/strong&gt;&lt;br&gt;
Triggers receive up to 200 records per invocation. Data Loader batches and Bulk API chunks can deliver all 200 together, so every trigger and test should assume a full list rather than a single record.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can I catch a LimitException in Apex?&lt;/strong&gt;&lt;br&gt;
No. A try-catch block cannot handle a limit exception, and the transaction rolls back. Check usage proactively with Limits.getQueries() and Limits.getLimitQueries(), and design code to stay well below each cap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use a Flow or an Apex trigger?&lt;/strong&gt;&lt;br&gt;
Use a Flow for simple declarative logic that admins maintain. Use Apex for unit-tested bulk behavior, complex maps, or callouts. Both share per-transaction limits, so neither is safe when it queries inside a loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When should I use Queueable instead of Batch Apex?&lt;/strong&gt;&lt;br&gt;
Use Queueable for small follow-up jobs started by a transaction. Use Batch Apex for large record sets, because limits reset for each batch execution. Queueable runs as one asynchronous transaction with higher caps than synchronous code.&lt;/p&gt;

</description>
      <category>salesforce</category>
      <category>100daysofcode</category>
      <category>crm</category>
      <category>mulesofthackathon</category>
    </item>
    <item>
      <title>Zoho Integration Services in Node.js: Fixing Expiring Webhook Channels</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Tue, 10 Nov 2026 05:05:04 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/zoho-integration-services-in-nodejs-fixing-expiring-webhook-channels-dip</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/zoho-integration-services-in-nodejs-fixing-expiring-webhook-channels-dip</guid>
      <description>&lt;p&gt;Your Deals webhook worked for exactly one hour, then Zoho CRM stopped calling your server. There was no error and no alert, only a growing gap between the CRM and your downstream database. This is a frequent silent failure in Zoho integration services built on push events. Zoho’s notification API defaults a channel to a one-hour lifetime and caps it at one day. Below, we build a Node.js receiver and a renewal job that survive both expiry and duplicate deliveries. For the wider picture, see &lt;a href="https://www.oodles.com/zoho/7144783?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_49" rel="noopener noreferrer"&gt;how Zoho integration services handle real-time sync in enterprise stacks&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Zoho Integration Services you need three parts: a channel registrar, a renewal job, and an idempotent receiver. Zoho CRM’s Notifications API sends a POST to your notify_url when a watched event fires. The body carries the module, record IDs, operation, channel ID, and your token. It does not carry the full record.&lt;/p&gt;

&lt;p&gt;Zoho’s documentation states that channel expiry can be at most one day after enabling, and defaults to one hour if omitted or set longer. The stack here is Node.js 20, Express, Redis (ioredis), and node-cron. You also need an OAuth client with the ZohoCRM.notifications.ALL scope and a public HTTPS endpoint. That endpoint is exposed to open traffic: Cloudflare’s State of Application Security report (2024) put API traffic at a median 58 percent of dynamic traffic, so verify every call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keeping Zoho Integration Services Alive Past Channel Expiry&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Register with an explicit expiry, renew on a schedule shorter than that expiry, and backfill after any failure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Register the Channel With a Verification Token&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Zoho echoes your token back in every callback, so the receiver can reject spoofed posts. Set the expiry yourself, because the one-hour default is the usual cause of the silence.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// register.js: create a channel that Zoho calls on Deals changes&lt;br&gt;
export async function registerChannel(accessToken, channelId) {&lt;br&gt;
  // Why: stay under the 24h ceiling so Zoho keeps our expiry instead of the 1h default&lt;br&gt;
  const expiry = new Date(Date.now() + 23 * 3600 * 1000).toISOString();&lt;br&gt;
  const res = await fetch("&lt;a href="https://www.zohoapis.com/crm/v7/actions/watch" rel="noopener noreferrer"&gt;https://www.zohoapis.com/crm/v7/actions/watch&lt;/a&gt;", {&lt;br&gt;
    method: "POST",&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Zoho-oauthtoken ${accessToken}&lt;/code&gt;, "Content-Type": "application/json" },&lt;br&gt;
    body: JSON.stringify({ watch: [{&lt;br&gt;
      channel_id: channelId,&lt;br&gt;
      events: ["Deals.create", "Deals.edit"],&lt;br&gt;
      channel_expiry: expiry,&lt;br&gt;
      token: process.env.ZOHO_NOTIFY_TOKEN, // Why: echoed back so we can verify the sender (max 50 chars)&lt;br&gt;
      notify_url: "&lt;a href="https://api.example.com/zoho/notify" rel="noopener noreferrer"&gt;https://api.example.com/zoho/notify&lt;/a&gt;",&lt;br&gt;
    }] }),&lt;br&gt;
  });&lt;br&gt;
  return res.json();&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Step 2: Renew Early and Backfill the Gap&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Renewing every six hours leaves several retry chances before the 23-hour expiry lands. If a renewal fails, assume events were missed and replay them.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// renew.js: extend the channel every 6 hours, replay missed changes on failure&lt;br&gt;
cron.schedule("0 */6 * * *", async () =&amp;gt; {&lt;br&gt;
  const token = await getAccessToken(); // assumed helper that refreshes the OAuth token&lt;br&gt;
  const expiry = new Date(Date.now() + 23 * 3600 * 1000).toISOString();&lt;br&gt;
  const res = await fetch("&lt;a href="https://www.zohoapis.com/crm/v7/actions/watch" rel="noopener noreferrer"&gt;https://www.zohoapis.com/crm/v7/actions/watch&lt;/a&gt;", {&lt;br&gt;
    method: "PATCH", // Why: updates the existing channel instead of creating a second one&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Zoho-oauthtoken ${token}&lt;/code&gt;, "Content-Type": "application/json" },&lt;br&gt;
    body: JSON.stringify({ watch: [{ channel_id: CHANNEL_ID, channel_expiry: expiry }] }),&lt;br&gt;
  });&lt;br&gt;
  // Why: a failed renewal may hide a silent gap since the last event we saw&lt;br&gt;
  if (!res.ok) await backfillSince(await redis.get("last_event_at"));&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Here backfillSince calls the Deals records endpoint with an If-Modified-Since header and queues each returned ID.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Acknowledge Fast, Deduplicate, and Weigh the Trade-offs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Answer Zoho first, then do the work. A slow database write inside the handler turns a healthy endpoint into a retry source.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// receiver.js: verify, acknowledge, dedupe, enqueue&lt;br&gt;
app.post("/zoho/notify", express.json(), async (req, res) =&amp;gt; {&lt;br&gt;
  const { token, ids = [], operation, channel_id } = req.body;&lt;br&gt;
  if (token !== process.env.ZOHO_NOTIFY_TOKEN) return res.sendStatus(401); // Why: reject spoofed calls&lt;br&gt;
  res.sendStatus(200); // Why: ack before any slow work&lt;br&gt;
  await redis.set("last_event_at", new Date().toISOString());&lt;br&gt;
  for (const id of ids) {&lt;br&gt;
    // Why: NX collapses concurrent duplicate deliveries into one job&lt;br&gt;
    const fresh = await redis.set(&lt;code&gt;dedupe:${channel_id}:${id}:${operation}&lt;/code&gt;, 1, "EX", 30, "NX");&lt;br&gt;
    if (fresh) await queue.add("sync-deal", { id });&lt;br&gt;
  }&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;The 30-second window has a cost: it can swallow a legitimate second edit. So the worker fetches the record and skips it only if Modified_Time is not newer than the stored value. Polling is the alternative. Zoho CRM charges one credit for most read calls, so polling one module every minute costs 1,440 calls a day before any record changes. Events cost calls only when data moves, and a light If-Modified-Since poll remains a safety net.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our Zoho integration services projects at [Oodles](oodles.com. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Channel expiry is the silent failure: Zoho caps it at one day and defaults to one hour, so always set it explicitly.&lt;br&gt;
Renew on a schedule well under the expiry, and treat a failed renewal as a signal to backfill.&lt;br&gt;
Notifications carry IDs, not records, so the worker must fetch and compare Modified_Time to stay idempotent.&lt;br&gt;
A short Redis SET NX window absorbs duplicates, but only a timestamp check protects legitimate rapid edits.&lt;br&gt;
Event-driven sync saves credits over fixed-interval polling, while a slow If-Modified-Since poll covers gaps.&lt;/p&gt;

&lt;p&gt;Questions about your own sync? Share them in the comments, or talk to us about &lt;a href="//oodles.com/contact-us"&gt;Zoho Integration services&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are Zoho integration services?&lt;/strong&gt;&lt;br&gt;
Zoho integration services connect Zoho apps such as CRM, Books, and Desk to each other or to external systems. They use REST APIs, webhooks, and Deluge scripting to sync data, and they include authentication, error handling, and monitoring.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How long do Zoho CRM notification channels last?&lt;/strong&gt;&lt;br&gt;
Zoho CRM channels expire at most one day after you enable them. If you omit channel_expiry or set it beyond one day, Zoho applies a one-hour default. Renew on a schedule shorter than the expiry.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do Zoho CRM webhooks include the full record?&lt;/strong&gt;&lt;br&gt;
No. The notification carries the module, record IDs, operation, channel ID, and your token. Your worker then fetches the record through the Records API. Setting return_affected_field_values to true adds changed field values to the payload.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do you stop duplicate Zoho notifications from running twice?&lt;/strong&gt;&lt;br&gt;
Return a 200 immediately, then dedupe with a short-lived Redis key using SET NX. In the worker, compare Modified_Time with the stored value. Together they make processing idempotent even if the same event arrives twice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use polling or notifications for Zoho CRM sync?&lt;/strong&gt;&lt;br&gt;
Use notifications for freshness and credit savings, and keep a light If-Modified-Since poll as a safety net. Polling one module every minute costs 1,440 calls daily, while events cost calls only when records change.&lt;/p&gt;

</description>
      <category>zoho</category>
      <category>integration</category>
      <category>erp</category>
      <category>crm</category>
    </item>
    <item>
      <title>How to Stop Double-Allocated Stock in Logistics Management Solutions</title>
      <dc:creator>Sanya Mittal</dc:creator>
      <pubDate>Mon, 09 Nov 2026 07:08:54 +0000</pubDate>
      <link>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-stop-double-allocated-stock-in-logistics-management-solutions-57ab</link>
      <guid>https://dev.to/sanya_mittal_a509a2c50a2d/how-to-stop-double-allocated-stock-in-logistics-management-solutions-57ab</guid>
      <description>&lt;p&gt;Two warehouse workers confirm the last 12 units of a SKU within the same second, and both orders succeed. This happens in logistics management solutions whenever stock is a mutable counter updated by concurrent services. Retries from a flaky carrier API make it worse. This article shows a ledger-based reservation pattern in Python and PostgreSQL that prevents oversell. It follows the same principle behind &lt;a href="https://www.oodles.com/inventory-warehouse-management-/2172960/case-study/client-project-spotlight:-future-proofing-logistics-ops-with-open-source-erp-by-oodles?utm_source=devto&amp;amp;utm_medium=referral&amp;amp;utm_campaign=backlink&amp;amp;utm_content=devto_article_48" rel="noopener noreferrer"&gt;how logistics management solutions work in enterprise systems&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The scenario: an order service, a warehouse service, and a tracking service all write to one inventory store. The stack is Python 3.12, psycopg 3, and PostgreSQL 16. You need a table per warehouse-SKU pair and an order API that retries on timeout.&lt;/p&gt;

&lt;p&gt;Data quality is the usual failure point. McKinsey’s 2023 supply chain survey reported that 52 percent of companies had adoption difficulties caused by the quality of their planning data. A counter that drifts under concurrency produces exactly that kind of bad data. &lt;br&gt;
chainstoreage&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building a Reservation Ledger for Logistics Management Solutions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In logistics management solutions a reservation ledger replaces the stock counter with append-only rows. Available stock is the sum of all rows, so no update can overwrite another.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Model Stock as Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Store every change as a signed row. Receipts add units, reservations subtract them, and releases add them back.&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
CREATE TABLE stock_ledger (&lt;br&gt;
  id         BIGSERIAL PRIMARY KEY,&lt;br&gt;
  sku        TEXT NOT NULL,&lt;br&gt;
  warehouse  TEXT NOT NULL,&lt;br&gt;
  delta      INT  NOT NULL,        -- Why: signed value makes SUM() the available stock&lt;br&gt;
  kind       TEXT NOT NULL,        -- receipt | reserve | release&lt;br&gt;
  idem_key   TEXT UNIQUE,          -- Why: a retried request cannot insert twice&lt;br&gt;
  created_at TIMESTAMPTZ DEFAULT now()&lt;br&gt;
);&lt;br&gt;
CREATE INDEX ON stock_ledger (sku, warehouse);  -- Why: keeps the SUM() scan narrow&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Reserve Under a Lock With an Idempotency Key&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Take a per-SKU lock, check the key, check availability, then insert. All four actions run in one transaction.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import psycopg&lt;/p&gt;

&lt;p&gt;def reserve(conn, sku, wh, qty, key):&lt;br&gt;
    with conn.transaction():&lt;br&gt;
        # Why: serializes writers per SKU without locking the whole table&lt;br&gt;
        conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (f"{sku}:{wh}",))&lt;br&gt;
        # Why: a retried request returns the first result instead of reserving twice&lt;br&gt;
        if conn.execute("SELECT 1 FROM stock_ledger WHERE idem_key=%s", (key,)).fetchone():&lt;br&gt;
            return "duplicate"&lt;br&gt;
        (avail,) = conn.execute(&lt;br&gt;
            "SELECT COALESCE(SUM(delta),0) FROM stock_ledger WHERE sku=%s AND warehouse=%s",&lt;br&gt;
            (sku, wh)).fetchone()&lt;br&gt;
        if avail &amp;lt; qty:&lt;br&gt;
            return "insufficient"  # Why: reject before writing, so the ledger stays clean&lt;br&gt;
        conn.execute(&lt;br&gt;
            "INSERT INTO stock_ledger (sku,warehouse,delta,kind,idem_key) "&lt;br&gt;
            "VALUES (%s,%s,%s,'reserve',%s)", (sku, wh, -qty, key))&lt;br&gt;
        return "reserved"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Pick a Locking Strategy for Logistics Management Solutions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Advisory locks suit hot SKUs because contention stays per key. Row locks on a counter table are simpler but block unrelated reads. Optimistic versioning avoids locks, yet it pushes retry logic into every caller.&lt;/p&gt;

&lt;p&gt;The ledger has one cost: SUM() grows with history. Write a periodic snapshot row per SKU and sum only rows after it. Do this once a single SKU passes a few hundred thousand rows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-World Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In one of our logistics projects at &lt;a href="//oodles.com"&gt;Oodles&lt;/a&gt;, a Shanghai-based logistics provider needed inventory, order processing, and real-time tracking in one open-source ERP (enterprise resource planning) system. We gave all three modules a single stock model, so reservations and shipment updates read the same records. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaways&lt;/strong&gt;&lt;br&gt;
Append-only rows remove lost updates because no writer overwrites another writer’s value.&lt;br&gt;
A unique idempotency key turns retried API calls into harmless no-ops.&lt;/p&gt;

&lt;p&gt;Per-SKU advisory locks limit contention to the item being reserved.&lt;br&gt;
Snapshot rows keep the ledger sum fast once history grows.&lt;br&gt;
Reject insufficient stock before the insert, so the ledger holds only true events.&lt;/p&gt;

&lt;p&gt;Questions about this pattern? Share them in the comments, or contact us about &lt;a href="//oodles.com/contact-us"&gt;Logistics Management Solutions&lt;/a&gt; for your stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What causes overselling in logistics management solutions?&lt;/strong&gt;&lt;br&gt;
Overselling occurs when two services read the same stock value and both write a reservation. Without a lock or atomic check, each sees enough units. Retried requests without idempotency keys create the same duplicate reservations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why use a ledger instead of a stock counter?&lt;/strong&gt;&lt;br&gt;
In logistics management solutions a ledger records each change as an immutable row, so concurrent writers never overwrite each other. It also gives an audit trail for reconciliation. The cost is a growing table, which snapshots keep manageable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Are PostgreSQL advisory locks safe in production?&lt;/strong&gt;&lt;br&gt;
Yes, when used transaction-scoped with pg_advisory_xact_lock, because PostgreSQL releases them at commit or rollback. Session-level locks risk leaking under connection pooling, so avoid them with tools like PgBouncer in transaction mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How does an idempotency key prevent duplicate reservations?&lt;/strong&gt;&lt;br&gt;
The client sends a unique key per logical request. A unique constraint on that key means a retry either hits the stored row or fails the insert, so the reservation happens exactly once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should reservations expire automatically?&lt;/strong&gt;&lt;br&gt;
Yes. Unpaid or abandoned orders hold stock indefinitely otherwise. Insert a release row from a scheduled job when a reservation passes its time limit, so the ledger stays the single source of truth.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
