<?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: Rokas Remeika</title>
    <description>The latest articles on DEV Community by Rokas Remeika (@rokasr).</description>
    <link>https://dev.to/rokasr</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%2F4115889%2Fd47aaddd-9898-41e0-a1a3-cd4dc7d64b96.png</url>
      <title>DEV Community: Rokas Remeika</title>
      <link>https://dev.to/rokasr</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rokasr"/>
    <language>en</language>
    <item>
      <title>A Scheduled Call Needs an Explicit Transition Table</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Fri, 27 Nov 2026 17:01:52 +0000</pubDate>
      <link>https://dev.to/rokasr/a-scheduled-call-needs-an-explicit-transition-table-2c8l</link>
      <guid>https://dev.to/rokasr/a-scheduled-call-needs-an-explicit-transition-table-2c8l</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 7 November 2026.&lt;/p&gt;

&lt;p&gt;When a dispatcher, a dial RPC, a media server webhook, and a reconciliation loop all write to the same call status field, the last writer always wins. Webhooks are delivered at least once and unordered, so late events can overwrite terminal states and resurrect completed calls. To stop this, model the call lifecycle as a single explicit transition table. Route every update through a guarded write path, reject any transition not explicitly defined in the table, and make terminal states truly immutable so duplicate events become harmless no-ops.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A scheduled outbound call sitting in a state nothing owns, showing as ringing hours after the line went dead.&lt;/li&gt;
&lt;li&gt;A completed call flipping back to active when a late webhook lands.&lt;/li&gt;
&lt;li&gt;Two handlers writing conflicting statuses within the same second, resulting in the last writer winning regardless of logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;A scheduled call is touched by at least four independent writers during its lifecycle. The task queue dispatcher claims the reservation, the dial RPC places the outbound leg, the media server sends room webhooks, and the reconciliation loop cleans up lingering database rows.&lt;/p&gt;

&lt;p&gt;If each of these independent writers sets a status field directly, the call lifecycle is only implicit. Ordering across these distributed systems is merely a hope, not a guarantee. Every out-of-order event and every duplicate webhook becomes an unguarded write directly to your database.&lt;/p&gt;

&lt;p&gt;Webhook delivery is at-least-once and unordered by design. The media server does not guarantee that a tear-down event will arrive after a participant-joined event. Because the stream is unordered, adopting a "later message wins" strategy is wrong by construction. It applies a sequential assumption to a fundamentally asynchronous stream, guaranteeing that delayed events will overwrite the current truth.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Extract the event logs for a call that resurrected from a completed state to an active state. Look at the timestamps. Expect to see a delayed media server webhook arriving seconds or minutes after the tear-down event, which confirms the system is blindly accepting writes.&lt;/li&gt;
&lt;li&gt;Query your task queue and webhook handler logs for the same call ID within a one-second window. Expect to find overlapping writes where the final database status matches the slowest network commit rather than the actual sequence of events.&lt;/li&gt;
&lt;li&gt;Count calls stuck in a ringing or dispatching state for more than an hour. Expect a non-zero count, confirming that state writes are being dropped, overwritten, or stalling without a mechanism to advance or terminate them.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I model the call lifecycle as one explicit transition table with a single guarded write path. Instead of applying every update that arrives, the system validates the requested transition against the explicit table. It rejects any transition not found in the table instead of applying it.&lt;/p&gt;

&lt;p&gt;The state machine runs on five live states and five terminal states. The live states progress predictably from pre-dispatch to dispatching, ringing, and active, eventually reaching completed.&lt;/p&gt;

&lt;p&gt;The five terminal states accept no further transitions at all. They are strictly immutable. When a late duplicate webhook fires against a terminal reservation, the transition check fails. The event becomes a logged no-op rather than a resurrected call, preserving the integrity of the completed state.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check whether terminal states accept updates. Inspect whether transition rejections cluster on dispatching-to-active pairs rather than terminal states. This discriminates between a missing legal shortcut and out-of-order webhook delivery landing after call teardown.&lt;/li&gt;
&lt;li&gt;Check how concurrent writes are handled at the database level. Review the SQL or ORM update path for the status field. If calls sit in ringing past the 45 s timeout with zero rejected transitions, an upstream writer stalled rather than losing a write race.&lt;/li&gt;
&lt;li&gt;Check the event delivery guarantees published by your media server. Measure the duration calls remain in dispatching and ringing against their configured timeout. This discriminates an abandoned or stalled upstream writer from concurrent handler contention.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The four independent writers
&lt;/h2&gt;

&lt;p&gt;The task dispatcher initiates the process by claiming a call from the database. It updates the state to dispatching, signaling to other workers that the task is owned.&lt;/p&gt;

&lt;p&gt;Immediately after, the dial RPC negotiates with the carrier to place the leg. Once the carrier signals progress, the RPC updates the database state to ringing.&lt;/p&gt;

&lt;p&gt;Simultaneously, the media server observes the realtime room. When a participant joins or room state changes, the media server emits webhooks to the application. These webhooks attempt to move the state to active or completed.&lt;/p&gt;

&lt;p&gt;Finally, a background reconciliation loop sweeps the database to catch failures. It checks for stalled calls and attempts to terminate them.&lt;/p&gt;

&lt;p&gt;Every one of these writers operates with different latency profiles.&lt;/p&gt;

&lt;h2&gt;
  
  
  Designing the explicit transition table
&lt;/h2&gt;

&lt;p&gt;Fixing the race condition requires removing raw write access. The update path must become a requested transition from a known current state to a desired next state.&lt;/p&gt;

&lt;p&gt;The implementation is a strict mapping of allowed paths. A pre-dispatch call can become dispatching. A dispatching call can become ringing. A ringing call can become active. An active call can become completed.&lt;/p&gt;

&lt;p&gt;When a component requests a state change, the database query enforces the transition table using a conditional update. The SQL UPDATE statement includes a status condition matching the expected previous state. If the row has already progressed, the conditional update modifies zero rows, and the application knows the transition was rejected.&lt;/p&gt;

&lt;p&gt;The five terminal states act as a one-way door. Once a call hits a terminal state, there are no valid outgoing transitions defined in the table. The conditional update will always fail, permanently locking the row against late webhooks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Documenting the shortcut transition
&lt;/h2&gt;

&lt;p&gt;You cannot design a rigid state machine for distributed systems without acknowledging dropped signals. Strict adherence to a linear path will break legitimate calls when the underlying platform misses an event.&lt;/p&gt;

&lt;p&gt;There is exactly one documented shortcut transition in my table: moving straight from dispatching to active, skipping the ringing state entirely.&lt;/p&gt;

&lt;p&gt;This shortcut is mandatory because the media server event stream does not guarantee a complete sequence. The room webhook can report the human participant joining without a matching agent-join event ever appearing on the stream.&lt;/p&gt;

&lt;p&gt;If the transition table rigidly demanded a ringing state first, it would reject the active update. The call would stall in dispatching forever, even though the human participant joined successfully.&lt;/p&gt;

&lt;p&gt;Writing this shortcut directly into the table, with the reasoning documented next to it, is a structural defense. It stops a future engineer from reviewing the explicit paths, assuming the shortcut is a bug, and fixing it back into a rejected transition.&lt;/p&gt;

&lt;h2&gt;
  
  
  Instrumenting the rejected transitions
&lt;/h2&gt;

&lt;p&gt;An explicit state machine transforms invisible race conditions into measurable data points. Every rejected transition is an observable event that tells you how the surrounding systems are behaving.&lt;/p&gt;

&lt;p&gt;I instrument the count of rejected transitions, keyed explicitly by the attempted from-state and to-state pair. This specific metric is exactly where out-of-order webhook delivery becomes visible. A spike in active-to-ringing rejections immediately highlights that the dial RPC is lagging behind the media server webhooks.&lt;/p&gt;

&lt;p&gt;I also track the time spent in each non-terminal state. A state that no writer is advancing becomes visible without custom alarm configurations. If a call sits in a ringing state for more than 45 s, the transition table is operating correctly, but the upstream signal that should advance it has failed. Reaping these stalled states safely requires splitting the reconciliation logic, as detailed in &lt;a href="https://dev.to/blog/the-scheduler-holds-stale-capacity-after-a-call-ends-or-kills-a-live-session-pre/"&gt;the scheduler holds stale capacity after a call ends or kills a live session prematurely&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The guarded write path
&lt;/h2&gt;

&lt;p&gt;Enforcing the transition table must happen at the data store level. Attempting to validate the transition in application memory introduces a race condition. Two webhook handlers will read the same active state, both will validate their transition locally, and both will overwrite the database sequentially.&lt;/p&gt;

&lt;p&gt;The single guarded write path relies on the database transaction enforcing the transition check. If the transaction layer is highly contended, probing before opening the transaction can save database resources. Evaluating the state cheaply before committing to an atomic check follows the same pattern used when &lt;a href="https://dev.to/blog/task-queue-dispatch-exceeds-capacity-despite-pre-check/"&gt;task queue dispatch exceeds capacity despite pre-check&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The core principle remains identical: the database must verify the current state atomically before committing the transition.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why does my completed call change back to active?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A delayed webhook from the media server arrived after the call tear-down event. If your status field accepts blind writes, this late event overwrites the completed state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I handle concurrent call state updates?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Model the call lifecycle using an explicit transition table. Enforce the update with a conditional database write that checks the current state before applying the new one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should the system reject out-of-order webhooks?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes, out-of-order events should be rejected if they violate the transition table. A late webhook against a terminal state should be logged as a no-op instead of altering the call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why skip the ringing state entirely?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The media platform may emit a participant joined event without ever sending an agent join event. Allowing a direct transition from dispatching to active prevents these calls from stalling.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/a-scheduled-call-needs-an-explicit-transition-table" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/a-scheduled-call-needs-an-explicit-transition-table&lt;/a&gt;&lt;/p&gt;

</description>
      <category>scheduling</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>A Wedged Call Bills Until the Server's 24-Hour Default When a Falsy Duration Is Dropped</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Wed, 25 Nov 2026 17:41:02 +0000</pubDate>
      <link>https://dev.to/rokasr/a-wedged-call-bills-until-the-servers-24-hour-default-when-a-falsy-duration-is-dropped-51lb</link>
      <guid>https://dev.to/rokasr/a-wedged-call-bills-until-the-servers-24-hour-default-when-a-falsy-duration-is-dropped-51lb</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 5 November 2026.&lt;/p&gt;

&lt;p&gt;A transport-level maximum call duration fails when the computed value evaluates to falsy. A bad estimate yielding zero, NaN, or undefined is silently omitted by the SDK from the placement request. Without that field, the SIP server substitutes its own generous default, typically 24 hours. Since your application worker is wedged, application-level timeouts fail to run. The fix is to strictly validate the duration, add a 90-second headroom margin, clamp the result to a hard 3600-second ceiling, and throw loudly if the value is non-positive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A call that stopped making progress hours ago remains active on the carrier side and continues to accrue charges.&lt;/li&gt;
&lt;li&gt;You set a maximum call duration when requesting the outbound dial, but it appears to have had no effect at all.&lt;/li&gt;
&lt;li&gt;There is no error returned by the placement request, no early truncation, and no obvious warning in the application logs.&lt;/li&gt;
&lt;li&gt;The leg outlives the conversation by hours, and the only indication of a problem is a 24-hour billing line item on your SIP trunk invoice.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;Application-level timeouts live entirely within your application process. When the process dies, the worker gets evicted by the orchestrator, or the agent loop wedges without exiting, none of those timeouts run. When the application goes quiet, the only thing that can still end the call is the transport-level duration cap sent with the initial placement request.&lt;/p&gt;

&lt;p&gt;Two traps sit in that transport cap. First, if the computed duration value evaluates to falsy in your language of choice (zero, NaN, or undefined resulting from a bad computation), the SDK omits the field from the placement request entirely. It does not send a zero. It sends nothing. The SIP server receives a request with no time limit and falls back to its own configured default. That default is typically 24 hours, which is exactly the runaway billing scenario the duration field was supposed to prevent.&lt;/p&gt;

&lt;p&gt;Second, if the cap is derived dynamically from an estimated call length with no fixed ceiling, a single bad estimate produces an absurd cap. A computation error that yields an absurdly large limit is syntactically valid and gets passed to the server, providing no actual cost protection. The combination of these two traps means a computed estimate is a dangerous thing to rely on for raw cost control.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Inspect the raw outbound placement request payload on a failing call using a network trace or the raw SDK debug logs. Expect to see the maximum duration field entirely missing, confirming the SDK dropped a falsy value before serialization.&lt;/li&gt;
&lt;li&gt;Log the raw computed duration variable just before it enters the placement call. Expect to see &lt;code&gt;NaN&lt;/code&gt;, &lt;code&gt;undefined&lt;/code&gt;, or &lt;code&gt;0&lt;/code&gt; on the specific runs that resulted in a runaway call.&lt;/li&gt;
&lt;li&gt;Check the carrier billing logs for the affected leg. Expect a duration of exactly 24 hours, or whatever the maximum allowed server-side session limit is for your specific SIP trunk.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;The architecture of an outbound AI call involves three independent lifecycles: the application worker, the WebRTC room, and the SIP leg. Your application code is responsible for managing the call under normal conditions. It decides when the conversation is over, tears down the agent, and issues the hangup command.&lt;/p&gt;

&lt;p&gt;When the application fails to do this, the SIP service acts as the backstop. Your code passes a maximum duration on placement, and the SIP process is the component that actually tears the leg down when that timer expires. The duration cap is enforced by the SIP infrastructure rather than scheduled inside your application code. The duration cap is a transport-level constraint enforced by the infrastructure, not a scheduled task running in your application.&lt;/p&gt;

&lt;p&gt;To guarantee this backstop works, the duration value must be strictly validated before it leaves your process. I compute the cap from the expected conversational length plus a generous headroom. Specifically, I take the estimated seconds and add 90 s of headroom. That 90 s buffer accounts for ringing and a slow goodbye sequence from the user.&lt;/p&gt;

&lt;p&gt;Once I have that computed value, I clamp it to a hard ceiling of 3600 s, regardless of what the estimate says. A one-hour call is the maximum acceptable risk for this specific deployment. Finally, I validate the integer. The code throws loudly on non-finite or non-positive values rather than letting them pass into the SDK. I treat this as a cost control that is independent of every application-level timeout, because its whole purpose is to work when your code is dead.&lt;/p&gt;

&lt;p&gt;A placement request that omits the duration field relies entirely on the server-side default rather than an explicit transport contract. The SIP server substitutes a 24-hour default when the duration parameter is omitted. Since I cannot control the upstream default across every provider, I assume an omitted field results in a 24-hour runaway, and I enforce a hard, validated integer locally to prevent the omission entirely.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check whether the SDK omitted the duration field entirely or passed an unchecked, oversized estimate. Inspect the raw placement request payload sent by the SDK. A missing field points to a falsy value in your local code. A present field on a runaway call points to an unchecked computation that produced an absurdly large cap.&lt;/li&gt;
&lt;li&gt;Check if the runaway call correlates with a specific conversational branch or logic path. Look at calls with zero or unusually large estimated lengths in your logs. Expect to find a division by zero or a missing configuration key that results in &lt;code&gt;NaN&lt;/code&gt;, ruling out a completely random SDK bug.&lt;/li&gt;
&lt;li&gt;Check whether the application process actually crashed or if the agent loop is still running but blocked. A crash rules out application-level timeouts immediately. A blocked loop means you have a deadlock that the transport cap must catch, which is exactly why the cap must not depend on the worker staying alive.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Validating the ceiling locally
&lt;/h2&gt;

&lt;p&gt;Any per-call cost control passed as an optional field has this exact failure mode. The SDK drops falsy values, the server substitutes a generous default, and you find out on the invoice. The rule is to validate the number before it leaves your process.&lt;/p&gt;

&lt;p&gt;Do not let a computed estimate be the only thing standing between you and a runaway leg. The calculation is derived from an estimated conversational duration computed by your application. If a computation encounters missing inputs or an arithmetic error, the resulting duration evaluates to zero or NaN. A simple &lt;code&gt;Math.max(calculated, minimum_safe_duration)&lt;/code&gt; followed by &lt;code&gt;Math.min(result, hard_ceiling)&lt;/code&gt; prevents the pipeline from outputting a value that the SDK will discard.&lt;/p&gt;

&lt;p&gt;If you are struggling with calls that hang open for entirely different reasons, such as the agent worker being dispatched after the SIP participant connects, you might be facing an ordering problem. Creating the room and dispatching the agent before you dial is necessary to prevent dead air. I cover that failure mode in &lt;a href="https://dev.to/blog/outbound-call-answers-to-dead-air-before-the-agent-joins/"&gt;/blog/outbound-call-answers-to-dead-air-before-the-agent-joins/&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Instrumenting the failure mode
&lt;/h2&gt;

&lt;p&gt;A transport cap acts as an infrastructure safety net rather than a standard lifecycle completion. When a call hits the maximum duration limit, the application has failed to tear it down gracefully.&lt;/p&gt;

&lt;p&gt;I count calls terminated by the transport cap as a distinct defect class rather than as a standard successful outcome. If a call hits the 3600 s ceiling, record the termination under the wedged-agent defect class in the per-call event log. This distinction is important because the SIP server does not send a special application error when it enforces the cap. It simply tears down the leg. If you do not explicitly track the duration against the cap, the teardown looks like a normal network disconnect.&lt;/p&gt;

&lt;p&gt;I also record the computed cap alongside the actual duration on every single call. This allows the 90 s headroom to be checked against reality. If a successful call consistently ends 85 s into the headroom, the estimate is too tight and risks truncating a legitimate conversation. If the call ends 10 s into the headroom, the buffer is overly generous.&lt;/p&gt;

&lt;p&gt;Finally, I count placement attempts rejected by the local validation guard. A rejected placement attempt is a saved runaway call. By tracking these rejections, you can trace the bad estimates back to their source in the duration computation without paying the carrier for a 24-hour debug session.&lt;/p&gt;

&lt;h2&gt;
  
  
  The interaction with application teardown
&lt;/h2&gt;

&lt;p&gt;The transport ceiling operates independently from the application teardown sequence. A healthy call should never hit this ceiling.&lt;/p&gt;

&lt;p&gt;When the application decides the call is over, it executes a graceful hangup. This involves finishing the final spoken sentence, closing the WebRTC room, and signaling the SIP participant to disconnect. Mistakes in this teardown sequence can also cause the room to outlive the conversation. Replacing a fixed sleep with an await on the current speech playout is the correct fix, which I detail in &lt;a href="https://dev.to/blog/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call/"&gt;/blog/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call/&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The transport ceiling does not replace the need for a correct application teardown. It exists solely to bound the financial damage when the application teardown logic fails entirely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why does my SIP call continue billing after the agent crashes?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The application worker orchestrates the call, and all application timeouts die with it. Without the worker, only the SIP server can end the call. If the placement request lacked a hard duration ceiling, the server falls back to its own limit, which is typically 24 hours.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is the maximum duration field missing from the placement request?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The SDK silently drops falsy values. If your computed duration evaluates to zero, NaN, or undefined, the SDK omits the field entirely before serialization. You must validate the integer and throw locally on non-positive values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How much headroom should I add to an estimated call duration?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I use 90 seconds of headroom on top of the estimated conversational length. This accounts for ringing and a slow goodbye. If the call takes longer to connect, the headroom prevents early truncation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I prevent a bad estimate from creating an absurd call limit?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Clamp the calculated duration to a hard ceiling regardless of the estimate. I use a strict 3600-second maximum for outbound calls. This guarantees that even a logic error in the estimation pipeline cannot result in a runaway leg.&lt;/p&gt;

&lt;p&gt;If the boundary this note describes is one you would rather own, &lt;a href="https://dev.to/migration"&gt;moving this layer off LiveKit Cloud&lt;/a&gt; moves it inside your own infrastructure.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/a-wedged-call-bills-until-the-servers-24-hour-default-when-a-falsy-duration-is-d" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/a-wedged-call-bills-until-the-servers-24-hour-default-when-a-falsy-duration-is-d&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sippstn</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The scheduler holds stale capacity after a call ends or kills a live session prematurely</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Mon, 23 Nov 2026 18:48:04 +0000</pubDate>
      <link>https://dev.to/rokasr/the-scheduler-holds-stale-capacity-after-a-call-ends-or-kills-a-live-session-prematurely-40h8</link>
      <guid>https://dev.to/rokasr/the-scheduler-holds-stale-capacity-after-a-call-ends-or-kills-a-live-session-prematurely-40h8</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 3 November 2026.&lt;/p&gt;

&lt;p&gt;The scheduler is guessing call states using timeouts instead of observing them. A time-based reconciler is correct for states the scheduler controls entirely, like dispatch wait times, but destructive for states owned by the media server. To fix it, split your reaping logic by state. Stop time-reaping in-flight reservations. Instead, cross-reference them against the media server API. Only force-end a reservation when the media server explicitly confirms the room is gone. If the room is live, extend the expected end timestamp and let the conversation continue.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Calls that are genuinely up get force-ended mid-conversation.&lt;/li&gt;
&lt;li&gt;A stale reservation holds capacity long after the media server ended the call.&lt;/li&gt;
&lt;li&gt;The scheduler believes the trunk is full and refuses new outbound dials, despite low actual traffic.&lt;/li&gt;
&lt;li&gt;Database active call counts drift away from the media server room counts in both directions over time.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;The scheduler uses a time-based reconciler to clean up stuck state. Reconcilers reap on age because age is the only signal available without querying an external system. This works for states the scheduler alone controls, like a reservation sitting in a pre-dispatch queue. It is destructive for states owned by another system. A reservation that is ringing, in flight, or active has its truth held by the media server, not by a timestamp in your database.&lt;/p&gt;

&lt;p&gt;Reaping an active call on age is a guess. That guess is wrong exactly when a real call runs longer than your maximum duration estimate. The result is that you break the most successful, longest-running conversations your agent has.&lt;/p&gt;

&lt;p&gt;On the flip side, if the media server shuts down a room but the webhook fails to reach the scheduler, the scheduler holds that reservation open indefinitely. If you rely solely on event streams to clear state, a missed event equals a permanent capacity leak. The system accumulates these leaks until it refuses to dial.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Query your scheduler logs for the exact reason a dropped call was terminated. Expect to find a reconciler or timeout reaper force-killing the session based on a maximum duration threshold, rather than a SIP BYE or room closure event. This confirms your reconciler is blindly reaping active state.&lt;/li&gt;
&lt;li&gt;Take the room ID of a reservation that the scheduler believes is currently active but has been running for an unusually long time. Run an explicit API call against your media server for that room ID. Expect the room to be absent from the media server's live room list. This confirms the media server tore it down, but the scheduler missed the transition.&lt;/li&gt;
&lt;li&gt;Count the total concurrent active reservations in your database and compare it to the live room count on the media server. Expect the database count to diverge from the media server room count. A persistent gap confirms you are leaking capacity through missed terminal events.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The danger of time-based reaping
&lt;/h2&gt;

&lt;p&gt;Age is a local property. You do not need to make a network call to know how old a database row is.&lt;/p&gt;

&lt;p&gt;A single call involves a SIP trunk, a media server, and a task queue. The scheduler sits at the top, handing out capacity. When the scheduler hands a slot to the media server, the scheduler no longer owns the lifecycle of that slot. The user and the media server own it.&lt;/p&gt;

&lt;p&gt;If you enforce a strict maximum duration on all calls, you guarantee that your best users will have a terrible experience. The reconciler wakes up, sees that the call has exceeded its duration estimate, and terminates the session. The user is mid-sentence, and the line goes dead.&lt;/p&gt;

&lt;p&gt;When terminal events are missed, the scheduler keeps the reservation active forever. Eventually, the capacity pool fills up with ghost calls. The scheduler believes the trunk is saturated and refuses to dial new outbound calls, even though the actual system is completely idle.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I split the reaping logic entirely based on which system owns the state. States that the scheduler owns and can decide alone are time-reaped against their specific service level. If a reservation never leaves the pre-dispatch state and passes its strict deadline, the reconciler fails it outright. The scheduler knows it never dispatched the work, so it safely cleans it up.&lt;/p&gt;

&lt;p&gt;In-flight states are never time-reaped. Instead, they are cross-referenced against the media server's live room list. A force-end on an active reservation happens only when the media server explicitly confirms the room is gone.&lt;/p&gt;

&lt;p&gt;When the room is still there and the call has simply outrun its estimated duration, the reconciler extends the expected end timestamp. It also escalates the log level for that reservation from a warning to an error on repeated overruns. That escalation raises the log level and does absolutely nothing else. No alert is raised, and the call is not killed. It makes the wedged case separable from a healthy long call when somebody actually goes looking in the logs.&lt;/p&gt;

&lt;p&gt;The reconciliation poll itself runs on a five-minute self-rescheduling cadence. This broad pass catches the silent leaks but is too slow for immediate capacity recovery. To fix the latency, I run a targeted sixty-second fast sweep that only checks reservations that recently changed state. This ensures ordinary drift is repaired in a minute, while keeping the broad API pass cheap.&lt;/p&gt;

&lt;p&gt;The instrumentation splits drift events by direction. You track when the scheduler thinks a call is live but the room is gone, versus when a room is live well past the expected end. You track the repeat-overrun count per reservation, which is the exact metric used to escalate a warning to an error. Finally, every repair event includes fast-sweep versus full-poll attribution, so you can tell which loop is doing the actual work.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Are the long calls actually being killed by the reconciler, or is the media server dropping them? Check the termination initiator. If the scheduler killed it on a timeout, the reconciler is at fault. If the media server initiated the disconnect, you have a network or provider issue, not a scheduling bug.&lt;/li&gt;
&lt;li&gt;Does the fast sweep see the same media server state as the full poll? Compare the results of the sixty-second check against the five-minute pass. If the fast sweep misses state changes but the five-minute poll catches them, your query filter for recently changed reservations is missing state transitions.&lt;/li&gt;
&lt;li&gt;Is the webhook endpoint actually receiving events from the media server? Check the ingress logs for room closure events. If the events never arrive, your primary signaling path is broken, and the reconciler is acting as the necessary fallback. If the events do arrive but the state stays stuck, your webhook handler is failing to update the database.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why did the reconciler kill a live call in progress?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The scheduler used a time-based timeout to reap long-running calls. When a conversation outran the maximum duration estimate, the reconciler forcefully ended it instead of checking if the media server still had an active room.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does the scheduler think a call is active after the room closed?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The webhook or event stream that normally signals the end of a call was dropped. Because the scheduler relies purely on incoming events, it never cleared the reservation, resulting in a ghost call holding capacity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I clear stale reservations holding capacity?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Run a periodic background task that cross-references active reservations against the media server's live room list. If the media server confirms the room is absent from its live room list, safely mark the reservation as terminal and release the trunk capacity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I alert on calls that run longer than estimated?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Do not raise an alert. Escalate the log level from warning to error on repeated overruns, which separates the wedged cases from healthy long calls when you investigate, but avoids waking you up for a successful conversation.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/the-scheduler-holds-stale-capacity-after-a-call-ends-or-kills-a-live-session-pre" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/the-scheduler-holds-stale-capacity-after-a-call-ends-or-kills-a-live-session-pre&lt;/a&gt;&lt;/p&gt;

</description>
      <category>scheduling</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Inbound Callers Vanish When the SIP Trunk Allowlist Silently Overflows</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Sat, 21 Nov 2026 15:01:41 +0000</pubDate>
      <link>https://dev.to/rokasr/inbound-callers-vanish-when-the-sip-trunk-allowlist-silently-overflows-4a05</link>
      <guid>https://dev.to/rokasr/inbound-callers-vanish-when-the-sip-trunk-allowlist-silently-overflows-4a05</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 1 November 2026.&lt;/p&gt;

&lt;p&gt;When legitimate inbound callers are silently dropped before reaching your telephony application, your per-trunk caller allowlist has likely exceeded its size limit. In a multi-tenant environment, individual tenant additions aggregate until they silently breach the trunk's capacity. The carrier rejects the over-limit numbers before they generate a SIP INVITE, leaving no trace in your logs. To fix this, build the allowlist as an explicit union across assigned tenants and apply hysteresis to the capacity check: warn at 80 percent, flag overflow at 100 percent, and clear the warning only when usage drops below 80 percent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Inbound calls from known, permitted numbers fail to connect, often dropping before the caller even hears a ringing tone.&lt;/li&gt;
&lt;li&gt;Your telephony application records zero trace of the call: no session, no routing decision, and no log line.&lt;/li&gt;
&lt;li&gt;From your side, the call simply never happened.&lt;/li&gt;
&lt;li&gt;The issue appears inconsistently. Older numbers continue to connect without issue, while newly assigned numbers for a tenant fail entirely.&lt;/li&gt;
&lt;li&gt;Because your application cannot report on calls it never receives, the complete absence of errors leads you to assume traffic was dropped inside your own infrastructure.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;A per-trunk caller allowlist has a hard size limit enforced by the carrier. When the union of permitted numbers across every tenant assigned to that trunk exceeds this limit, the entries that do not fit are simply absent from the carrier's routing table.&lt;/p&gt;

&lt;p&gt;Capacity is consumed by an aggregate that nobody explicitly owns. Each tenant addition is individually reasonable, and the total crosses a line no single change is responsible for.&lt;/p&gt;

&lt;p&gt;Because the limit is breached at the provider edge, the rejection happens before your code is ever involved. The carrier drops the unauthorized traffic without forwarding a SIP INVITE to your network. Your application cannot log a session it never receives, leaving you completely blind to the failure. The tenant assignment that caused the overflow is often days in the past, entirely divorcing the failure from your most recent deployment.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Count the distinct permitted numbers across all tenants assigned to the affected trunk. Expect this total to exceed the provider's documented allowlist limit, confirming an overflow state.&lt;/li&gt;
&lt;li&gt;Inspect the provisioned allowlist payload directly against the carrier trunk limit. Expect newly assigned tenant numbers beyond the capacity threshold to be absent from the active carrier allowlist.&lt;/li&gt;
&lt;li&gt;Temporarily remove one known-working number from the tenant configuration to free up a slot, add the failing number, and retry the test call. Expect the call to succeed, which isolates the issue strictly to capacity exhaustion rather than a malformed number format.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I build the allowlist as an explicit union across all assigned tenants. Rather than relying on independent updates from isolated tenant configurations, a centralized builder aggregates the permitted numbers, deduplicates them, and calculates the total payload before interacting with the trunk API. If you have tenants sharing identical resources, you also need strict rules for how traffic is directed once it gets through. I wrote about that handling in &lt;a href="https://dev.to/blog/deterministic-inbound-sip-routing-when-tenants-share-a-phone-number/"&gt;Deterministic Inbound SIP Routing When Tenants Share A Phone Number&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I give the capacity check hysteresis rather than relying on a single threshold. A naive check at the boundary flaps constantly. If one number is added and removed repeatedly right at the limit, it toggles the alert state and trains everyone on the engineering team to ignore it.&lt;/p&gt;

&lt;p&gt;To prevent the capacity check from flapping, I tuned the thresholds deliberately. I warn at 80 percent of allowlist capacity. I flag an overflow and increment a persistent counter at exactly 100 percent. I clear the state only when usage drops back below 80 percent. This creates a buffer zone that forces capacity planning rather than reactive firefighting.&lt;/p&gt;

&lt;p&gt;I run a pre-flight inspection before any enforcement rollout that inspects each trunk's policy mode. This process refuses to proceed if any trunk is already enforcing rather than notifying. A capacity mistake must produce a notification you can act on, instead of a caller who cannot get through. Failing the pre-flight inspection when any trunk enforces rather than notifies ensures capacity mistakes yield actionable notifications instead of dropped calls.&lt;/p&gt;

&lt;p&gt;For instrumentation, I log the allowlist size against the per-trunk limit on every rebuild, per trunk. I keep a persistent overflow counter in the metrics, and I treat any non-zero value as a correctness event rather than a statistic. I also keep rejections at the trunk and rejections by my own routing logic as entirely separate numbers, ensuring that edge drops never pollute the application-layer admission metrics. If you are struggling with absent logs during provisioning, you might also be dealing with API idempotency issues, which I cover in &lt;a href="https://dev.to/blog/inbound-sip-calls-produce-no-logs-or-trunk-provisioning-creates-duplicates/"&gt;Inbound SIP Calls Produce No Logs, Or Trunk Provisioning Creates Duplicates&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I built and operate this mechanism on a raw carrier SIP trunk where overflowing numbers are silently omitted, but boundary behavior across carriers varies. Because the rejection happens before your code is involved, you cannot rely on an inbound SIP rejection code reaching your network. You must verify your carrier's trunk-level behavior directly, because your application cannot report on calls it never receives.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;The total count of provisioned numbers against the carrier's hard capacity limit. Expect a breach to confirm the allowlist overflow, ruling out any application-layer routing bugs.&lt;/li&gt;
&lt;li&gt;The trunk policy mode in your infrastructure configuration. Expect an "enforce" state to explain the silent drops, whereas a "notify" state rules out the allowlist as the cause of the missing inbound calls.&lt;/li&gt;
&lt;li&gt;Trunk-level rejections against application-level routing rejections. Expect non-zero rejections at the trunk to isolate capacity drops at the carrier edge from downstream routing logic failures.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The Danger of Shared Capped Resources
&lt;/h2&gt;

&lt;p&gt;Any shared, capped resource fed by independent contributors needs an owner for the aggregate and hysteresis on the threshold. In a multi-tenant telephony system, no individual tenant cares about the total trunk capacity. They only care that their specific numbers are permitted.&lt;/p&gt;

&lt;p&gt;Without an aggregate owner, the system drifts toward failure automatically. A tenant adding a single phone number is an operation that should always succeed. When it fails because another tenant added numbers days earlier, the failure boundary is drawn in the wrong place. The engineering team must own the aggregate limit, monitor its growth, and provision new trunks or request limit increases long before the threshold is breached.&lt;/p&gt;

&lt;p&gt;Warning at 80 percent of capacity provides actionable visibility before callers are dropped.&lt;/p&gt;

&lt;h2&gt;
  
  
  Securing Visibility Before the Application
&lt;/h2&gt;

&lt;p&gt;Any control that rejects traffic before your application runs needs its own visibility. Your application cannot report on calls it never receives, which means the absence of errors is not evidence of the absence of rejections.&lt;/p&gt;

&lt;p&gt;When a carrier drops a call, they are doing exactly what you told them to do: blocking unauthorized traffic. They view the overflowed numbers as unauthorized because they never received them in the allowlist payload. To them, the system is working perfectly.&lt;/p&gt;

&lt;p&gt;By treating the generation of the allowlist as a critical control plane operation, you move the failure domain from the carrier's black box into your own observable infrastructure. Logging the size of the list during the rebuild step is the only way to prove what the carrier actually knows. If the rebuild process logs an overflow, you know exactly why the calls are failing, even if the SIP traces remain completely empty.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why do legitimate inbound calls drop without leaving any logs?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A trunk-level caller allowlist likely exceeded its size limit. The provider rejects overflowing numbers before they reach your network, so no SIP INVITE or error log is ever generated in your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I stop capacity alerts from flapping on every update?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement hysteresis by using multiple thresholds for the capacity check. Warn when capacity reaches 80 percent, flag an overflow at 100 percent, and clear the warning only when usage drops back below 80 percent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What should I check before rolling out trunk policy changes?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Run a pre-flight inspection to verify the trunk policy mode. Refuse to proceed if the trunk is set to enforce rather than notify, ensuring capacity mistakes produce actionable notifications instead of dropped calls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I monitor an allowlist that rejects calls outside my system?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Log the allowlist size against the trunk limit on every configuration rebuild. Maintain a persistent overflow counter and treat any non-zero value as a serious correctness event rather than a standard operational statistic.&lt;/p&gt;

&lt;p&gt;If the boundary this note describes is one you would rather own, &lt;a href="https://dev.to/migration"&gt;a self-hosted deployment you control&lt;/a&gt; moves it inside your own infrastructure.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/inbound-callers-vanish-when-the-sip-trunk-allowlist-silently-overflows" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/inbound-callers-vanish-when-the-sip-trunk-allowlist-silently-overflows&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sippstn</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Completed calls are recorded as hangups because the disconnect wins the write race</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Thu, 19 Nov 2026 16:06:03 +0000</pubDate>
      <link>https://dev.to/rokasr/completed-calls-are-recorded-as-hangups-because-the-disconnect-wins-the-write-race-fph</link>
      <guid>https://dev.to/rokasr/completed-calls-are-recorded-as-hangups-because-the-disconnect-wins-the-write-race-fph</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 28 October 2026.&lt;/p&gt;

&lt;p&gt;Your analytics over-report caller hangups because two asynchronous events race to write the session end reason. When a call completes naturally, the agent lifecycle sets a success reason. However, the caller usually hangs up immediately after the final prompt. This triggers a SIP disconnect event, which arrives milliseconds later and overwrites the success state with a hangup reason. To fix this, replace last-write-wins with a precedence rule. Once a terminal reason is set by the agent lifecycle, make the database ignore subsequent disconnect events. The first writer with a valid reason must win.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Calls whose transcript shows the agent delivering its closing line and finishing properly are stored with a hangup reason.&lt;/li&gt;
&lt;li&gt;The call outcome field systematically over-reports the person hanging up, skewing overall analytics.&lt;/li&gt;
&lt;li&gt;Every downstream conclusion built on the end reason is wrong, because the telemetry is corrupted at the source.&lt;/li&gt;
&lt;li&gt;The wrongness is systematically biased toward the calls that went perfectly well, masking actual success rates and causing you to chase false drop-offs.&lt;/li&gt;
&lt;li&gt;Every downstream conclusion built on the end reason is systematically biased toward misclassifying successful calls as user drop-offs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;Two writers can set the reason a call ended, and they are racing to update the same database row.&lt;/p&gt;

&lt;p&gt;The agent's own lifecycle state machine sets a specific reason when it finishes properly. When the agent delivers its final sentence and the conversational logic decides no further turns are expected, it pushes a terminal success status to the call record.&lt;/p&gt;

&lt;p&gt;Separately, a hangup watcher fires when the far end disconnects. At the SIP layer, a network &lt;code&gt;BYE&lt;/code&gt; message arrives, tearing down the media session and triggering a participant-disconnected event.&lt;/p&gt;

&lt;p&gt;On a real call, the human hangs up the instant the agent stops talking. This physical response happens extremely fast. The caller hits the red button often within the exact same second the audio playout ends, sometimes before the closing bookkeeping from the agent lifecycle has fully landed in your persistent storage.&lt;/p&gt;

&lt;p&gt;The disconnect writer, reacting to the SIP &lt;code&gt;BYE&lt;/code&gt;, arrives last. If your database uses a basic last-write-wins update strategy, the disconnect event overwrites a reason that was already correct.&lt;/p&gt;

&lt;p&gt;Last-write-wins turns the phrase "the call completed" into "they hung up". The calls most likely to be misattributed are the ones that reached a natural ending, because those are exactly the ones where the person hangs up immediately after the final word. A call where the user gets frustrated and hangs up mid-sentence is correctly labelled as a hangup. A call where the user waits politely and hangs up at the end is incorrectly labelled as a hangup.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Record the time between the lifecycle reason being set and the disconnect event arriving on a per-call basis. Expect to see sub-second gaps on the calls marked as hangups that have complete transcripts. A gap in the tens or hundreds of milliseconds confirms the two events are reacting to the exact same conversational milestone.&lt;/li&gt;
&lt;li&gt;Compare the final transcript state to the end reason in the database. Expect a mismatch where the transcript has a natural closing line (like a goodbye) but the database reason is recorded as a caller disconnect.&lt;/li&gt;
&lt;li&gt;Count how many times an update to the end-reason field replaces an existing value for the same call ID. Expect this counter to increment precisely on the calls that ended cleanly, which is the direct measure of how often the race fires in production.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I designed the telemetry system to make the close reason single-writer by precedence rather than by timing.&lt;/p&gt;

&lt;p&gt;The fix is defining which reasons are terminal, and allowing only a transition from a no-reason state to a terminal reason. If the agent lifecycle has already ended with a valid reason, that reason wins. The database update logic explicitly checks the existing state of the row. If a terminal reason is already present, the new write is discarded.&lt;/p&gt;

&lt;p&gt;The disconnect path may still record that the far end went away in a separate connection-state field. You still need to know when the socket actually closed for infrastructure reasons. But it may not replace an existing terminal reason for the business outcome of the call.&lt;/p&gt;

&lt;p&gt;First writer with a real reason wins, and the last writer never wins by virtue of being last.&lt;/p&gt;

&lt;p&gt;This pattern generalises across realtime systems. Any per-entity outcome field written by more than one asynchronous source needs a precedence rule, not a mutex. A mutex only ensures the database does not corrupt the row during simultaneous writes. It does nothing to prevent a logically older event from overwriting a logically newer one. This is the difference between telemetry you can make decisions from and telemetry that quietly encodes a race condition.&lt;/p&gt;

&lt;p&gt;To ensure this behaviour does not regress when new close reasons are added, I assert it in a unit test. The test delivers the two events (lifecycle completion and SIP disconnect) to the state machine in both possible orders. The assertion requires that the first valid terminal reason survives, and any subsequent reason is silently dropped.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Look at your database update queries for call completion. If the transcript terminates before the agent reaches its closing line, the caller genuinely hung up mid-conversation rather than suffering a late disconnect write race.&lt;/li&gt;
&lt;li&gt;Inspect the timestamp delta between the last agent audio frame and the incoming participant disconnect webhook. If they are nearly identical, it confirms the caller hung up in response to the closing prompt. (If you notice the agent's last sentence is actually truncated on the caller's side before they hang up, you might have a playout sleep issue instead. See /blog/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call/ for that diagnosis).&lt;/li&gt;
&lt;li&gt;Check whether an unhandled provider error terminated the session before the agent finished talking. If a mid-session provider error occurred, classify whether the session error terminated the call prematurely rather than letting the lifecycle complete cleanly.&lt;/li&gt;
&lt;li&gt;Review your session finalisation logs. If the disconnect event arrived before lifecycle bookkeeping completed, the hangup watcher recorded its outcome before the terminal reason could be committed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The cost of treating connection state as business state
&lt;/h2&gt;

&lt;p&gt;A webhook fires when the peer disconnects, so it feels natural to wire that directly into your analytics as a user-disconnected outcome.&lt;/p&gt;

&lt;p&gt;An AI agent has a lifecycle that exists independently of the socket carrying the audio. The agent can complete its goal, summarise the interaction, and decide to end the call. That decision is a rich, high-fidelity business event.&lt;/p&gt;

&lt;p&gt;A SIP &lt;code&gt;BYE&lt;/code&gt; is a low-fidelity network event. It tells you nothing about the user's intent. Overwriting a high-fidelity conversational outcome with a low-fidelity network outcome destroys data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing the precedence rule in code
&lt;/h2&gt;

&lt;p&gt;The implementation requires defining an explicit state machine for the call record.&lt;/p&gt;

&lt;p&gt;You cannot rely on the framework to handle this, because the framework does not know what your integration considers a successful outcome. The framework only knows that the session ended.&lt;/p&gt;

&lt;p&gt;I use a structured failure taxonomy for the termination reasons. Each reason carries a rank or a boolean flag indicating whether it is terminal. When an event attempts to update the call record, the update handler reads the current state.&lt;/p&gt;

&lt;p&gt;If the current state is empty or in-progress, the update proceeds. If the current state is already a terminal reason, the handler compares the incoming reason against the existing one. If the incoming reason is a network disconnect and the existing reason is a conversational success, the update is silently dropped. This requires per-call event-sourced traceability.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why does my voice agent transcript show a natural end but the reason is hangup?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The caller hung up immediately after the final prompt, triggering a network disconnect event. This late network event overwrites the earlier conversational success status in your database. You are seeing the result of a last-write-wins race condition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I prevent network teardowns from overwriting success states?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement a state machine precedence rule for the call outcome field. Define success as a terminal state. Once the agent writes a terminal state, configure the database update logic to reject any subsequent network disconnect reasons.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I delay the SIP BYE event so the success state lands first?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No. Adding a fixed sleep to race conditions only hides the problem until the system is under load. You must fix the architecture by making the outcome field single-writer by precedence rather than by timing.&lt;/p&gt;

&lt;p&gt;If the boundary this note describes is one you would rather own, &lt;a href="https://dev.to/migration"&gt;owning the TURN and SIP path directly&lt;/a&gt; moves it inside your own infrastructure.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/completed-calls-are-recorded-as-hangups-because-the-disconnect-wins-the-write-ra" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/completed-calls-are-recorded-as-hangups-because-the-disconnect-wins-the-write-ra&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sippstn</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The scorer is a program too, and it is wrong more often than the agent</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Tue, 17 Nov 2026 16:30:35 +0000</pubDate>
      <link>https://dev.to/rokasr/the-scorer-is-a-program-too-and-it-is-wrong-more-often-than-the-agent-2ogf</link>
      <guid>https://dev.to/rokasr/the-scorer-is-a-program-too-and-it-is-wrong-more-often-than-the-agent-2ogf</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 8 October 2026.&lt;/p&gt;

&lt;p&gt;When a voice agent evaluation pipeline scores a flawless transcript as unclassifiable, or flags an agreement as a refusal, the scoring logic itself is introducing noise. Deterministic regex matches are brittle against spontaneous speech. Callers elide expected words, causing false negatives, or use negated constructions like "I would not say no" that falsely trigger decline signatures. The fix is a two-tier scoring system. Tier one uses strict deterministic matching for predictable phrasing, defaulting to an explicit unresolved state instead of failure. Tier two escalates only the unresolved transcripts to an independent model for adjudication.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;An evaluation run that a human reads as a flawless conversation comes back unclassifiable.&lt;/li&gt;
&lt;li&gt;A paraphrase that means the opposite of a refusal gets filed as a refusal by the pipeline.&lt;/li&gt;
&lt;li&gt;The pass rate numbers move between sweeps because the scoring code changed, not because the agent prompt or model did.&lt;/li&gt;
&lt;li&gt;A perfect run scores as unmatched because a signature expected a word the speaker elided in spontaneous speech.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;The scorer is a software program too, and it is wrong more often than the voice agent it evaluates. Deterministic matching over transcripts is cheap and reproducible, but it is brittle in exactly the way spontaneous speech is unpredictable.&lt;/p&gt;

&lt;p&gt;A typical home-grown scorer relies on standard regular expressions to parse the agent's output transcription. A signature written from the prompt's phrasing expects a specific word the speaker elided in conversation. Spontaneous speech regularly omits connecting words that deterministic substring rules rely on to detect a match. When the elided word is missing from the transcript, deterministic matching fails to trigger and leaves a successful run unmatched. The aggregate metrics move because the measurement instrument failed to match the transcript, not because the agent failed the scenario.&lt;/p&gt;

&lt;p&gt;Conversely, consider a decline signature. You want to know if the user refused to answer a qualification question. The signature looks for "no", "not", or "refuse". The user says, "I would not say no to that." The regex engine hits the "not" and the "no", and the run is permanently marked as a refusal. The caller was actually agreeing, but because negated constructions contain the exact stems a decline signature expects, the agreement is punished.&lt;/p&gt;

&lt;p&gt;Neither error is visible in the aggregate pass rate. Both errors quietly move the number you are about to make a deployment decision on. This quietly corrupts the evaluation signal before any deployment decision is made.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Read ten transcripts from your last sweep that scored as unclassifiable. Expect to find at least one where the caller clearly agreed or declined but used a synonym or elided the verb your regex expected.&lt;/li&gt;
&lt;li&gt;Search your false-negative bucket for negated phrasing. Look for the words "not", "never", or "wouldn't" sitting immediately next to your target decline stems. Expect to see successful agreements falsely flagged as rejections.&lt;/li&gt;
&lt;li&gt;Run your scoring script against a static batch of agent transcripts, using two different recent commits of your scoring code. Expect the total pass rate to shift. A shift confirms that your scoring instrument is injecting noise independently of agent behavior.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The fix
&lt;/h2&gt;

&lt;p&gt;I fixed this by splitting the evaluation pipeline into a two-tier scoring system. The architectural pattern was straightforward: cheap-and-exact first, expensive-and-judgmental second, with an explicit unresolved state sitting between them.&lt;/p&gt;

&lt;p&gt;Tier one was deterministic substring and stem matching. It resolved runs at zero marginal cost wherever the phrasing was highly predictable. I maintained this deterministic matching in the two languages the agent was validated in end to end (the agent itself is configurable across 60 languages, live-validated in two, and scoring signatures existed for those two).&lt;/p&gt;

&lt;p&gt;Crucially, tier one was not allowed to guess. If a transcript did not match the expected signatures perfectly, it did not default to a failure, and it did not default to a pass. Anything it could not confidently resolve was emitted as an explicit &lt;code&gt;unresolved&lt;/code&gt; state and passed to tier two.&lt;/p&gt;

&lt;p&gt;Tier two was an independent adjudication pass executed by a separate large language model. This model judged the raw transcript alone, without seeing the agent's internal state. It was invoked only for the runs that tier one left unresolved.&lt;/p&gt;

&lt;p&gt;To keep tier one honest and prevent the regex rules from becoming an unmaintainable mess, I enforced two discipline rules. First, signatures were loosened only against speech that was actually observed in the real world. When a run exposed a gap in the matching logic, that exact run was recorded in the codebase directly next to the new signature. This made the loosening traceable rather than folkloric. Second, every single decline signature carried its own negation. I required that a phrase meaning the opposite could not possibly be matched by the same stems.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check the default verdict of your scoring function. Inspect whether unclassified runs reflect callers eliding expected prompt phrasing or the agent failing to elicit the turn. Expect an unresolved state. A default failure rules out accurate visibility into missing signatures, meaning your pass rate is artificially low.&lt;/li&gt;
&lt;li&gt;Measure the ratio of deterministically resolved runs versus escalated runs in a single sweep. Expect the vast majority to resolve in tier one. If the adjudicator is processing most of the sweep, this rules out a healthy deterministic tier and confirms your signatures are too narrow.&lt;/li&gt;
&lt;li&gt;Check your scorer test suite for negation coverage. Run a test where a mock user says "I am not refusing". Expect the scorer to explicitly bypass the refusal signature. A false positive here rules out the agent being at fault for declining agreement metrics.&lt;/li&gt;
&lt;li&gt;Check the audit trail of your signature modifications. Look at the last regex you loosened. Expect to see a link to the specific transcript that forced the change. A missing trail rules out an evidence-based evaluation process, meaning developers are likely introducing false positives by guessing.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why the scorer test suite is roughly two-thirds the size of the scorer
&lt;/h2&gt;

&lt;p&gt;If the scorer is broken, every other metric is compromised. To guarantee its accuracy, I built a dedicated regression test suite for the scoring code itself.&lt;/p&gt;

&lt;p&gt;My scorer test suite ended up roughly two-thirds the size of the entire scorer codebase. Every time a new edge case was discovered in a real conversation, a mock transcript representing that exact phrasing was added to the test matrix.&lt;/p&gt;

&lt;p&gt;This test coverage was the only way to ensure that adding a new negation check did not accidentally break an existing agreement signature.&lt;/p&gt;

&lt;h2&gt;
  
  
  Instrumenting the adjudication boundary
&lt;/h2&gt;

&lt;p&gt;When you delegate decisions to a second model, you have to watch the boundary between the deterministic code and the LLM. I instrumented the pipeline to count the runs resolved deterministically versus those escalated to adjudication, and I logged this ratio per sweep.&lt;/p&gt;

&lt;p&gt;Every escalated run was archived alongside the exact transcript the adjudicator saw. This was critical for debugging. When a sweep produced a surprising number, I needed to know if the agent changed its behavior or if the adjudicator hallucinated a verdict. Archiving the prompt and transcript together meant I could replay the exact adjudication step in isolation.&lt;/p&gt;

&lt;p&gt;This architecture generalizes to any transcript-scored evaluation, voice or text. It gives you reproducibility where the language is predictable and coverage where it is not, and it keeps the model-judged fraction small enough to review by hand. Behavioral edits to a voice agent trade failure classes against each other, a dynamic I detailed when writing about how a &lt;a href="https://dev.to/blog/voice-agent-prompt-change-improved-one-behavior-but-broke-another/"&gt;prompt change improved one behavior but broke another&lt;/a&gt;. If the scorer randomly misclassifies those trade-offs, you will inevitably revert good changes and ship regressions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why do flawless agent runs score as unclassifiable?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Callers routinely elide the specific verbs or nouns your deterministic signatures expect. When a required word is missing, the regex fails to match, leaving a successful run unclassified.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does the scorer flag user agreements as refusals?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Users often speak in negated constructions, such as "I would not refuse". The transcript contains the exact stems a decline signature looks for, causing a false positive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How should a transcript scorer handle unrecognized phrasing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It must default to an explicit unresolved state. Defaulting to a pass or a fail masks the fact that your signatures are missing common phrasing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a two-tier evaluation system?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It applies cheap, exact deterministic matching first. Any transcript it cannot resolve is escalated to a second tier, where an independent LLM adjudicates the conversation.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/the-scorer-is-a-program-too-and-it-is-wrong-more-often-than-the-agent" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/the-scorer-is-a-program-too-and-it-is-wrong-more-often-than-the-agent&lt;/a&gt;&lt;/p&gt;

</description>
      <category>eval</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Task Queue Retry Called The Customer Twice And An Exists Check Will Not Stop It</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Sun, 15 Nov 2026 14:22:10 +0000</pubDate>
      <link>https://dev.to/rokasr/task-queue-retry-called-the-customer-twice-and-an-exists-check-will-not-stop-it-5991</link>
      <guid>https://dev.to/rokasr/task-queue-retry-called-the-customer-twice-and-an-exists-check-will-not-stop-it-5991</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 22 September 2026.&lt;/p&gt;

&lt;p&gt;An at-least-once task queue retrying a telephony placement can ring a person twice, even if you check whether a call record already exists. This happens because the platform's native webhooks can create the call record before your dial RPC returns, and because a queue's retry timeout often fires while the first attempt is still ringing. To fix it, you need two markers. First, a post-placement marker written only by your dial code to prove the call happened. Second, a pre-placement attempt marker that locks the number for a window sized to your ringing timeout plus the queue's acknowledgment budget.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;An at-least-once task queue retries the outbound dial task, and the same person is called twice within a minute.&lt;/li&gt;
&lt;li&gt;The queue metrics show only one logical task being processed, but the carrier logs show two distinct INVITEs leaving your infrastructure.&lt;/li&gt;
&lt;li&gt;The guard clause most people reach for (checking if the call record already exists before dialing) either never fires, or it fires on the first attempt and blocks a call that was never actually placed.&lt;/li&gt;
&lt;li&gt;The trap worth stating plainly: "does a record for this call exist" feels like idempotency and is not, as soon as more than one component can create that record.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;Two separate problems stack together to defeat a basic existence check. First, the call record is rarely authored by a single writer. The platform's native room-started webhook is fast and can easily create the record before the dial RPC returns. Because webhooks and the dial process run concurrently, the record existing is not evidence that a dial happened. An existence check in this state is simply reading a marker somebody else wrote.&lt;/p&gt;

&lt;p&gt;Second, the dangerous window occurs exactly between the moment we start placing the call and the moment we record the successful placement. Outbound ringing takes tens of seconds. A task queue that retries based on an acknowledgment timeout or visibility budget will re-enter the dial pipeline exactly during this window. Because the first attempt has not returned yet, nothing has been written to confirm placement. By definition, the existence check allows the second attempt through, resulting in a duplicate call.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Log every queue redelivery of a dial task as an explicit event. This makes retries visible as events rather than being inferred from duplicate INVITEs.&lt;/li&gt;
&lt;li&gt;Correlate the webhook arrival time with the dial RPC return time for a single session. Expect to see the platform's room-started webhook arriving and writing to your database before the dial RPC completes its execution, proving that record existence is untrustworthy as an idempotency key.&lt;/li&gt;
&lt;li&gt;Measure the time from the attempt marker being written to the placement marker being written, per call. Count attempts refused by the in-flight window separately from attempts refused as already placed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;To prevent double-dials under queue retries, I use two markers with entirely different jobs. Relying on document existence is fundamentally flawed when multiple writers are involved. You have to pick fields that only the dial path can write, and check those fields exclusively.&lt;/p&gt;

&lt;p&gt;First, a post-placement marker serves as the final proof that a dial actually happened. This is written only by the dial path, and only after the placement RPC returns successfully. You check this field to know if the side effect is complete, never the bare document existence.&lt;/p&gt;

&lt;p&gt;Second, a pre-placement attempt marker closes the in-flight window. This is written immediately before firing the RPC. It acts as a bounded lock: any attempt that starts inside a specific validity window after an existing attempt marker is refused. I size that window to the 45 s ringing timeout plus the queue's acknowledgment budget. This guarantees that a genuinely in-flight attempt blocks a retry, while a dead attempt eventually releases the lock instead of wedging the phone number forever.&lt;/p&gt;

&lt;p&gt;Enforce the same window at webhook-processing time, so the guard does not depend on which path runs first.&lt;/p&gt;

&lt;p&gt;This is a general rule I apply to any at-least-once queue placed in front of a side effect that costs money and reaches a human. The marker that proves the side effect happened must be written by the code that performed it. The window between starting the action and recording it needs its own bounded lock sized from the transport's real duration plus the queue's redelivery budget.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check the timestamp of the platform's room-started webhook against the return time of the dial RPC. A webhook that writes the call record before the RPC returns rules out document existence as a reliable proof of placement.&lt;/li&gt;
&lt;li&gt;Compare the task queue's visibility timeout against your hard ringing timeout. A visibility timeout shorter than 45 seconds rules out the queue's native retry being safe for outbound dialling, because the queue will inevitably redeliver tasks while the phone is still ringing.&lt;/li&gt;
&lt;li&gt;Review the exact order of your outbound placement operations. Room creation that happens after the SIP participant is created rules out being able to cleanly correlate native platform webhooks, because those webhooks will arrive before your database has the routing metadata they need.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Ordering the placement operations
&lt;/h2&gt;

&lt;p&gt;Outbound placement consists of three operations, and their order is load-bearing. Getting the order wrong guarantees downstream failures that look like idempotency bugs or leaked resources.&lt;/p&gt;

&lt;p&gt;Create the room first, and carry the routing metadata the webhooks will need directly in the room creation request. Creating the room without metadata means the platform's native room and participant webhooks arrive carrying only platform identifiers. They know the room, but they know nothing about your domain model. Anything that tries to resolve the tenant or number from a webhook has nothing to resolve from, forcing expensive database round trips. When you supply the metadata upfront, the webhook handler becomes a pure function of the event.&lt;/p&gt;

&lt;p&gt;Create an explicit agent dispatch next. Doing this ensures a worker is in the room before the phone actually rings. Dispatching the agent after the SIP participant means the worker can still be starting when the callee picks up. If the person answers to two seconds of nothing before the agent starts existing, the caller experience is broken from the first word. You can read more about resolving the timing of the first word in &lt;a href="https://dev.to/blog/outbound-call-greets-before-the-callees-audio-is-subscribed/"&gt;Outbound call greets before the callee's audio is subscribed&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Create the SIP participant last, with wait-until-answered, dial tone playback, and a 45 s ringing timeout. Give it a deterministic participant identity derived from the session id so every later event can be correlated without a lookup.&lt;/p&gt;

&lt;p&gt;From the moment the room exists, you own it. Wrap everything after room creation so that every failure branch deletes the room before returning the error. Any failure after that point (a placement error, a classification error, an unexpected throw) leaks a room that a worker will occupy until the empty timeout expires. I log room creation and room deletion as paired events, so an unmatched creation is a highly visible leaked failure branch.&lt;/p&gt;

&lt;h2&gt;
  
  
  Safe retries versus dangerous double-dials
&lt;/h2&gt;

&lt;p&gt;Retrying a placement is only safe when the failure provably happened before any INVITE left the box. This interacts directly with stale-trunk self-healing.&lt;/p&gt;

&lt;p&gt;SIP trunk state is often held in a store that is not necessarily durable across restarts. A Redis instance without persistence configured is a common shape. The platform mints new trunk ids when it comes back online. Every id you cached in process memory or persisted next to a phone number now points at nothing. The failure is invisible until someone tries to dial, and because the error is a validation error rather than a call outcome, it is easy to classify as a bad number instead of broken infrastructure.&lt;/p&gt;

&lt;p&gt;I built a narrow self-heal for this exact scenario. On that one specific error, I evicted the cached id, re-resolved the trunk by its stable name, and retried the placement exactly once. The narrow match is a strict safety property. That specific error is raised during request validation before any signalling occurs, so a retry provably cannot ring a person twice. If you widen the match to catch generic connection timeouts, you have built a double-dial machine.&lt;/p&gt;

&lt;p&gt;You can read the full teardown of that specific error state in &lt;a href="https://dev.to/blog/outbound-calls-fail-with-trunk-does-not-exist-after-a-restart/"&gt;Outbound Calls Fail With Trunk Does Not Exist After A Restart&lt;/a&gt;. The question that decides whether an automatic retry is safe is always the same: can this failure have had a side effect before it was raised?&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why did the queue retry while the phone was still ringing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The queue's acknowledgment budget or visibility timeout is shorter than the carrier's ringing timeout. If a call rings for 45 seconds but the queue expects an acknowledgment sooner, it will assume the worker failed and redeliver the task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can I just check if the call record exists before dialing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No. Platform webhooks often create the call record in your database before the dial RPC completes. Checking for record existence might read a marker written by a webhook, leading you to block a call that was never actually placed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I prevent a failed attempt from locking out the number forever?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Size the pre-placement lock to a bounded window. Combine the 45 s ringing timeout and the queue's acknowledgment budget. If the lock is older than that window, the previous attempt is genuinely dead and you can safely retry.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is it ever safe to retry a failed SIP placement?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Retrying is only safe if the failure provably occurred before any SIP signalling left your infrastructure. Validation errors like a missing trunk identifier are safe to retry, while carrier timeouts are not.&lt;/p&gt;

&lt;p&gt;If the boundary this note describes is one you would rather own, &lt;a href="https://dev.to/migration"&gt;taking ownership of the infrastructure underneath&lt;/a&gt; moves it inside your own infrastructure.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/task-queue-retry-called-the-customer-twice-and-an-exists-check-will-not-stop-it" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/task-queue-retry-called-the-customer-twice-and-an-exists-check-will-not-stop-it&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sippstn</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Task Queue Executions Climb Indefinitely With No Visible Errors</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Fri, 13 Nov 2026 14:58:41 +0000</pubDate>
      <link>https://dev.to/rokasr/task-queue-executions-climb-indefinitely-with-no-visible-errors-3dg</link>
      <guid>https://dev.to/rokasr/task-queue-executions-climb-indefinitely-with-no-visible-errors-3dg</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 30 October 2026.&lt;/p&gt;

&lt;p&gt;When a task queue shows a monotonically growing execution rate but zero errors, a payload has likely been enqueued against the wrong self-rescheduling handler. If an accounting payload reaches a reconciliation loop that reschedules itself every five minutes, the handler processes the unknown payload silently and schedules its successor. Each dial attempt forks a brand new immortal chain. You must bind the payload type to the handler route at the enqueue boundary, and force the handler to reject unrecognized payloads instead of blindly perpetuating them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Task queue executions climb with dial volume and never come back down.&lt;/li&gt;
&lt;li&gt;Nothing errors, nothing retries, and no reservation is affected.&lt;/li&gt;
&lt;li&gt;Every individual execution looks functionally normal and exits with a success code.&lt;/li&gt;
&lt;li&gt;The system produces a background execution rate that grows monotonically with outbound dial volume.&lt;/li&gt;
&lt;li&gt;A cost line tracking worker compute mirrors this execution rate perfectly.&lt;/li&gt;
&lt;li&gt;Nobody notices the bug during functional testing because no call quality or scheduling logic fails. The shape of the bug has to be found by reading code rather than by noticing an outage.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;A usage-accounting task was enqueued against the reconciliation handler route rather than its own dedicated route. The reconciliation handler contract is to reschedule itself at the end of every execution. This is correct behaviour for the loop it belongs to, but it is catastrophic for a payload that was never meant to enter that loop.&lt;/p&gt;

&lt;p&gt;In a distributed call scheduling system, a reconciliation loop runs on a recurring schedule to audit system state. A reconciliation handler often runs as a continuous cycle. Instead of relying on a centralized scheduler, the worker processes its batch and enqueues its own subsequent execution with a five-minute delay. This design relies on each execution enqueueing its successor, which functions correctly until an unexpected payload enters the loop.&lt;/p&gt;

&lt;p&gt;When the usage-accounting payload arrived at the reconciliation route, the worker deserialized it. Because nothing in the self-rescheduling handler asked whether it should exist, it completed its run without error. It completed its run without throwing an exception and executed its final instruction: schedule the next tick.&lt;/p&gt;

&lt;p&gt;Each misrouted task became the root of a brand new self-rescheduling five-minute chain. One chain was created per dial attempt. The chains never terminated because nothing in a self-rescheduling handler asks whether it should exist. The implication of the five-minute reconciliation cadence is that, by arithmetic alone, each forked chain adds twelve executions an hour indefinitely. By arithmetic alone, each forked chain adds twelve executions an hour indefinitely, accumulating with every dial attempt. The system stayed functionally correct throughout. This is a cost and blast-radius bug, not a call-quality one, which is exactly why it survived normal code review.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Group your task queue executions by handler route and chart them over a twenty-four hour window. Expect to see one specific handler route climbing linearly with outbound call volume, while the rest remain flat. If you see the reconciliation route execution rate climbing in lockstep with dial volume while other handlers stay flat, you have found the leak.&lt;/li&gt;
&lt;li&gt;Inspect the raw payload of a recent execution on the runaway handler. Expect to find fields belonging to a completely different domain, like usage-accounting keys or dial-state identifiers, rather than the expected reconciliation state. This proves the route mismatch occurred at the source.&lt;/li&gt;
&lt;li&gt;Audit chain identity directly by counting distinct chain roots currently alive rather than bare executions. Expect to find the count of live chain roots climbing above one with dial volume rather than remaining a small constant.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The fix
&lt;/h2&gt;

&lt;p&gt;The remediation this points to requires a structural design change, rather than just pointing the task at the right route and walking away. You must bind the payload type to the handler route at the enqueue boundary and assert it. Do this in the same place the deterministic task name is asserted, so a mismatch fails loudly at enqueue instead of quietly at execution.&lt;/p&gt;

&lt;p&gt;Assert the payload type against the handler route directly at the enqueue boundary, in the same place the deterministic task name is asserted. Binding the payload type to the handler route ensures that an invalid route pairing fails immediately at task creation. The client validates that the route string exactly matches the expected handler for that specific payload class. If an accounting payload is submitted to the reconciliation route, the assertion fails loudly at enqueue instead of quietly at execution.&lt;/p&gt;

&lt;p&gt;Next, make self-rescheduling handlers refuse to reschedule on a payload shape they do not recognize. This turns a wrong task in the loop into a single logged rejection rather than a new immortal chain. The handler must explicitly validate that the data it receives is something it has the authority to perpetuate.&lt;/p&gt;

&lt;p&gt;Finally, audit chain identity directly. Count distinct chain roots rather than bare executions. The count of live loops is the number that should be exactly one. The count of executions is the number that hides the problem. One live chain is the correct count. Anything else is a bug.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check the queue error rate. A zero error rate rules out standard poison-pill retries and points to a self-perpetuating success path.&lt;/li&gt;
&lt;li&gt;Check the count of distinct chain roots currently alive against the expected baseline. A count exceeding one confirms that dial attempts are forking immortal poll chains.&lt;/li&gt;
&lt;li&gt;Check the cadence of the executions. A strict five-minute interval between runs matches the reconciliation loop schedule, pointing to a misrouted payload caught in that specific loop.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why code review misses routing bugs
&lt;/h2&gt;

&lt;p&gt;The most dangerous aspect of this failure mode is its silent correctness. When an engineer reviews an enqueue call, they look at the payload construction and the target queue. If the route string is imported from a shared constants file, a slip of autocomplete can easily select the reconciliation queue instead of the usage-accounting queue.&lt;/p&gt;

&lt;p&gt;Because the payload is valid JSON and the queue exists, the enqueue operation succeeds. Because the reconciliation worker is designed to catch generalized state payloads and ignore fields it does not care about, it does not crash. The worker simply processes the task, finds no actionable reconciliation work, and schedules the next tick. The only artifact is a compute bill that slowly creeps upward.&lt;/p&gt;

&lt;h2&gt;
  
  
  Counting loops instead of executions
&lt;/h2&gt;

&lt;p&gt;The reason this bug survives in production is a failure of instrumentation. We typically monitor task queues by looking at throughput, execution latency, and error rates. When this bug occurs, throughput goes up, latency remains low, and errors remain at zero. By all standard metrics, the system appears exceptionally healthy.&lt;/p&gt;

&lt;p&gt;To catch this, you need instrumentation focused on distinct chain roots currently alive, which should be a small constant. This is the number that would have caught this anomaly immediately had anything been counting loops instead of executions. You also need executions per handler broken out by payload type, so a payload arriving at a handler that should never see it is visible. Finally, enqueue-time assertion failures must be counted, because a rise means something upstream is routing wrongly.&lt;/p&gt;

&lt;h2&gt;
  
  
  The limits of this diagnosis
&lt;/h2&gt;

&lt;p&gt;I must state explicitly that while this defect occurred in a production distributed scheduling layer, my confidence is medium regarding how identically this presents across every third-party task framework. I have not mapped the exact routing mechanics of every available queue provider.&lt;/p&gt;

&lt;p&gt;However, the structural vulnerability generalizes completely. It applies to any queue where the handler route is chosen at enqueue time and any handler in the system reschedules itself. The dangerous combination is a routing mistake meeting a self-perpetuating contract, and it exists on every durable-task platform. The two defences carry over regardless of the framework you use: assert the payload and route pairing where the task is created, and never let a self-rescheduling handler perpetuate a payload it cannot definitively identify.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why are task queue executions climbing with no errors?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A payload was likely misrouted to a self-rescheduling handler. The handler processes the task silently and schedules a successor, creating an immortal chain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I stop a self-rescheduling queue loop?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You must configure the handler to explicitly reject and drop payloads it does not recognize. This prevents unknown tasks from being passed to the next execution tick.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does my reconciliation worker run more often than scheduled?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Outbound dials or external events are enqueuing tasks against the reconciliation route by mistake. Each errant task spawns a parallel execution chain that runs on the same cadence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I monitor runaway queue loops?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Track the count of distinct chain roots rather than bare executions. The number of active roots for a scheduled loop should be exactly one.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/task-queue-executions-climb-indefinitely-with-no-visible-errors" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/task-queue-executions-climb-indefinitely-with-no-visible-errors&lt;/a&gt;&lt;/p&gt;

</description>
      <category>scheduling</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Task Queue Dispatch Exceeds Capacity Despite Pre-Check</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Wed, 11 Nov 2026 14:47:07 +0000</pubDate>
      <link>https://dev.to/rokasr/task-queue-dispatch-exceeds-capacity-despite-pre-check-2f0e</link>
      <guid>https://dev.to/rokasr/task-queue-dispatch-exceeds-capacity-despite-pre-check-2f0e</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 26 October 2026.&lt;/p&gt;

&lt;p&gt;A single-stage admission path forces a structural failure under load. Opening a transaction for every scheduled task means rejected calls consume database resources and contend with valid ones. Trusting a fast read outside a transaction leads to race conditions where a call is dialed but capacity is already gone. The fix is a two-stage admission path. Probe capacity cheaply outside the transaction to drop hopeless candidates early, then perform an authoritative re-check atomically inside the transaction immediately before placement. The atomic result always wins.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Dispatch throughput collapses under a burst. Transactions pile up, contend, and retry during a burst while most of them were always going to be rejected for want of capacity.&lt;/li&gt;
&lt;li&gt;Transactions pile up, contend, and retry in your database or document store, even though the system was always going to reject most of them for lacking channel capacity.&lt;/li&gt;
&lt;li&gt;A dispatcher trusts a fast pre-check and dials a call the authoritative check would have refused.&lt;/li&gt;
&lt;li&gt;Legitimate inbound calls are starved and rejected because an outbound dialer surge consumed all available slots.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;Transactions are the expensive, contended resource in any scheduling system. When a burst of scheduled tasks wakes up, they all want to run at exactly the same time. If you use a single-stage admission path, you are forced into a structural trade-off.&lt;/p&gt;

&lt;p&gt;Opening a transaction for every due call means the calls that cannot possibly be admitted still pay the full price. They pay the full transaction cost and contend with the calls that can actually be admitted. The database spends all its time rejecting tasks instead of placing them.&lt;/p&gt;

&lt;p&gt;The mirror failure is skipping the transaction entirely because a cheap read said there was room. That cheap read is just a hint from the past. By the time the dial RPC fires and hits the carrier network, the capacity that the read saw may be completely gone. A fast read authorises a call that a strict transactional check would have blocked. Both of these are structural properties of a single-stage admission path.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Graph your database transaction contention against the scheduled task queue depth during a burst. Expect transaction contention and retries to rise with the volume of due tasks even when channel capacity is exhausted. This confirms that doomed calls are contending for database resources.&lt;/li&gt;
&lt;li&gt;Count the number of placed outbound dials against your authoritative concurrency check. Expect to see placed dials exceeding the strict limit if your dispatcher is trusting a stale read outside of a transaction boundary.&lt;/li&gt;
&lt;li&gt;Measure the inbound call rejection rate during a burst of scheduled outbound tasks. Expect to see inbound calls dropping when outbound tasks surge. This confirms that both traffic types are competing blindly for the exact same admission transaction pool.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I two-stage the admission path. I run a cheap probe outside any transaction to drop the hopeless candidates early, then I re-decide atomically inside the transaction immediately before placement.&lt;/p&gt;

&lt;p&gt;The atomic result wins every time. The probe has only one job: to reduce transaction pressure. It is never allowed to authorise a dial. If the probe says the system is full, the task backs off immediately without touching the database. If the probe says there is room, the task is allowed to attempt the expensive transaction.&lt;/p&gt;

&lt;p&gt;Inside that transaction, the system performs an authoritative re-check of the capacity pool and peak overlapping reservations before claiming a slot. If you want the exact database mechanics of that inside-transaction check, I wrote about &lt;a href="https://dev.to/blog/enforcing-maximum-concurrent-sip-calls-without-race-conditions/"&gt;enforcing maximum concurrent SIP calls without race conditions&lt;/a&gt;. The core rule here is that the final decision happens under a lock, but we only acquire that lock if the cheap probe told us it was worth trying.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Look at the ratio of opened admission transactions to successful channel allocations. Expect opened transactions to track admitted placements rather than total scheduled volume. If transaction volume scales with total due tasks rather than available channel capacity, transactions are contending before admission is decided. This rules out network capacity limits and points entirely to transaction pressure.&lt;/li&gt;
&lt;li&gt;Check the time elapsed between your capacity read and the actual dial RPC execution. Expect this gap to be under a few milliseconds. If the gap spans network calls or complex business logic, your read is stale. This rules out accurate capacity tracking and confirms a race condition.&lt;/li&gt;
&lt;li&gt;Review the concurrency limits for inbound versus outbound traffic. Expect to find a shared pool with no priority mechanism. If they share a hard cap without deferral logic, this rules out network capacity issues and points directly to your outbound dispatcher starving your inbound routes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Instrumenting the disagreement gap
&lt;/h2&gt;

&lt;p&gt;The most dangerous part of an optimistic filter is that it silently drifts. If the probe logic becomes too slow, or if the cache it reads from falls behind, it stops being a helpful hint and starts being a liability.&lt;/p&gt;

&lt;p&gt;To fix this, I instrument the gap between the two stages. I keep a counter of how often the probe and the authoritative transaction disagree. If the probe says there is room but the transaction says there is no capacity, that is a disagreement.&lt;/p&gt;

&lt;p&gt;I emit this counter into the event log as a first-class number. It is worth watching as a service level of its own, though nothing here watches it today. A rising disagreement rate means the probe is reading state that is too stale to be useful. It is buying you nothing but risk.&lt;/p&gt;

&lt;p&gt;This disagreement counter is the part almost nobody builds, and it is the only thing that tells you whether the optimisation is still safe six months later.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deriving dispatch mode from the task name
&lt;/h2&gt;

&lt;p&gt;Task queues often retry jobs. Sometimes a job needs to run aggressively, and sometimes it needs to act as a gentle backstop.&lt;/p&gt;

&lt;p&gt;Two dispatch rules sit alongside the admission control logic. The handler derives its own mode strictly from the task name prefix. A primary dispatch and a backstop dispatch run the exact same underlying code, but they run with different aggressiveness profiles.&lt;/p&gt;

&lt;p&gt;By pulling the mode from the task name prefix rather than a field inside the JSON payload, a handler can never guess or inherit the wrong role. If a payload gets corrupted, or if an engineer manually re-enqueues a job with a missing field, the task name remains intact.&lt;/p&gt;

&lt;h2&gt;
  
  
  Protecting inbound traffic from outbound bursts
&lt;/h2&gt;

&lt;p&gt;Admission control protects shared channel capacity as well as database availability.&lt;/p&gt;

&lt;p&gt;When inbound traffic surges, outbound dispatch defers rather than competing with it for the same channels. An inbound call is a real human being waiting on the carrier network right now. If you reject them, the call is gone permanently.&lt;/p&gt;

&lt;p&gt;An outbound call is a scheduled intent. A missed outbound attempt is reschedulable. If the system is busy processing a spike of inbound activity, the outbound dispatcher simply logs a deliberate deadline overcommit, backs off, and tries again later.&lt;/p&gt;

&lt;p&gt;I record the count of deliberate deadline overcommits. This makes the cost of the policy visible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why does dispatch throughput drop when scheduled calls burst?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Doomed calls are opening database transactions and contending for locks. You are paying the full database cost to reject a call because you lack a fast pre-check.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can I just check capacity before dialing to save database load?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A cheap read is a hint from the past. By the time the dial RPC fires, the capacity may be gone, leading to over-commitment. You must always re-verify inside a transaction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I know if my pre-check is reading stale data?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Keep a counter of how often the pre-check and the authoritative transaction disagree. A rising disagreement rate means the probe is reading state too stale to be useful and is buying you nothing but risk.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do inbound calls drop when the outbound dialer starts?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;They are competing for the same channels without priority. Outbound tasks must defer during inbound surges because outbound is reschedulable and inbound is not.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/task-queue-dispatch-exceeds-capacity-despite-pre-check" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/task-queue-dispatch-exceeds-capacity-despite-pre-check&lt;/a&gt;&lt;/p&gt;

</description>
      <category>scheduling</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Bounding Shutdown Retries By Attempt Count Strands The Transcript</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Mon, 09 Nov 2026 16:54:17 +0000</pubDate>
      <link>https://dev.to/rokasr/bounding-shutdown-retries-by-attempt-count-strands-the-transcript-5n1</link>
      <guid>https://dev.to/rokasr/bounding-shutdown-retries-by-attempt-count-strands-the-transcript-5n1</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 24 October 2026.&lt;/p&gt;

&lt;p&gt;When a voice agent worker shuts down, the framework gives it a fixed time window before killing the process. If your transcript persistence logic retries based on a maximum attempt count, the combined HTTP timeouts can exceed the shutdown window. The process dies mid-write, losing data that only existed in memory. The fix is to budget retries by wall clock. Give the operation a total time budget, and size it so the budget plus one maximum-length HTTP timeout remains strictly inside the framework's shutdown window.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Transcripts and end-of-call records go missing for calls that ended normally.&lt;/li&gt;
&lt;li&gt;The write operation is attempted, but the logs stop mid-attempt with nothing after them.&lt;/li&gt;
&lt;li&gt;The missing records look like flakiness, happening randomly across healthy instances.&lt;/li&gt;
&lt;li&gt;The failure gets significantly worse whenever the downstream storage service is slow, which is exactly when the end-of-call record matters most for debugging.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;When a worker process finishes a call or receives a termination signal, the framework running it initiates a teardown phase. The framework gives your shutdown callback a fixed window to clean up and save state. After that window expires, the framework or the host operating system kills the process entirely.&lt;/p&gt;

&lt;p&gt;Most persistence paths use standard retry libraries or custom loops that bound retries by attempt count. A network write might be configured to retry three times, with a ten-second HTTP timeout per attempt. This works perfectly during normal operation because the process will live indefinitely to see the attempts conclude.&lt;/p&gt;

&lt;p&gt;During teardown, the process is living on a fixed timer. A persistence path that bounds its retries by attempt count has a worst case measured in attempts, not seconds. Three attempts at a ten-second HTTP timeout can block for thirty seconds. If your framework gives you a twenty-two second graceful shutdown window, you have an eight-second deficit.&lt;/p&gt;

&lt;p&gt;The downstream service experiences a latency spike. Your first write attempt takes ten seconds and times out. Your second attempt takes ten seconds and times out. You start the third attempt. Two seconds later, the framework's shutdown timer expires. The process receives a SIGKILL while the write is in flight. The memory containing the final transcript is wiped, and data that existed only in that process is gone forever.&lt;/p&gt;

&lt;p&gt;The bound on your retry logic is real, but it is denominated in the wrong unit. Attempt counts bound the number of failures, not the time. Shutdown windows bound the time, not the failures.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Filter your logs for the worker process ID that handled the lost call, starting from the shutdown signal. Expect to see the persistence attempt begin, followed by a hard stop with no subsequent log lines indicating success or failure.&lt;/li&gt;
&lt;li&gt;Measure the timestamp gap between the shutdown signal and the final log line of the process. Expect this gap to match your framework's exact graceful shutdown timeout limit, proving the process was forcefully killed.&lt;/li&gt;
&lt;li&gt;Check the downstream storage service logs for the exact minute the call ended. Expect elevated latency or HTTP gateway timeouts that pushed the write duration past its normal baseline, triggering your retry loop.&lt;/li&gt;
&lt;li&gt;Compare the recorded wall-clock duration of the shutdown callback directly against the framework window in your call event logs. Expect the duration to reach the framework shutdown window limit without any subsequent log indicating completion.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;The fix is to budget the teardown persistence by wall clock instead of attempt count. You give the whole operation a total time budget, give each attempt its own HTTP timeout, and size them so that the budget plus one maximum-duration in-flight attempt still lands safely inside the shutdown window.&lt;/p&gt;

&lt;p&gt;Here is the sizing I run in production. The framework provides a 22-second shutdown await window. I give the end-of-call record write an 8-second total wall-clock budget. I give the HTTP client a 10-second per-attempt timeout.&lt;/p&gt;

&lt;p&gt;If the storage backend is struggling, the loop checks the wall clock. As long as the elapsed time is under 8 seconds, it fires another HTTP request. The worst-case scenario is an attempt starting right before the 8-second budget expires. That final attempt is allowed to block for its full 10-second timeout. The total time elapsed before the HTTP client times out and returns control to the loop is just under 18 seconds.&lt;/p&gt;

&lt;p&gt;That 18-second worst case fits cleanly against the 22-second shutdown await the framework gives me. The process has time to observe the final failure, log it cleanly, and exit on its own terms before the operating system brings the hammer down.&lt;/p&gt;

&lt;p&gt;The three numbers in that example are not the transferable part. The inequality is the transferable part: &lt;code&gt;(total_budget + per_attempt_timeout) &amp;lt; framework_shutdown_window&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You must write that exact arithmetic in a comment next to the constants in your code. The constraint is completely invisible from any one constant on its own. The next person to review the code will see an 8-second budget, decide it is too tight for a slow backend, raise it, and unknowingly break the system. They will not know what they broke because the increased budget still looks smaller than the 22-second shutdown window on its own. They will only find out when transcripts start vanishing again.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check if the session was ended by a function tool calling a teardown routine rather than a normal caller hangup. A tool tearing down the session immediately can cut off final audio and disrupt the lifecycle sequence; if this is the case, arming a pending closure fixes it, as detailed in /blog/voice-agent-end-call-tool-truncates-the-final-sentence-or-loses-the-callers-last/.&lt;/li&gt;
&lt;li&gt;Check the HTTP response codes returned by the downstream API just before the data loss. An HTTP 400 Bad Request indicates a malformed payload that failed instantly, ruling out timeout starvation. If the downstream storage service returned an HTTP gateway error, the request completed over the network rather than being terminated mid-flight.&lt;/li&gt;
&lt;li&gt;Check whether the worker process suffered an unexpected crash or host termination prior to the shutdown callback running. Check process supervisor logs to verify whether the process ran until the framework graceful shutdown timer expired.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Instrumenting the teardown path
&lt;/h2&gt;

&lt;p&gt;Fixing the timeouts stops the data loss, but you need instrumentation to prove the fix holds over time. A teardown sequence is invisible to standard request tracing because the client has already disconnected.&lt;/p&gt;

&lt;p&gt;I record the shutdown callback wall-clock duration per call and emit it as a structured log event. This allows me to query the duration and compare it against the framework's window across the entire fleet. If the persistence operation starts creeping closer to the 18-second worst case, I can see the degradation before it starts dropping records.&lt;/p&gt;

&lt;p&gt;Additionally, give an incomplete transcript write its own named failure code on the call's end event. Do not let it land as a generic internal error. When a failure code specifically names the persistence timeout on the end event, you isolate a wall-clock write failure immediately instead of investigating it as a generic error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generalizing the pattern
&lt;/h2&gt;

&lt;p&gt;This failure mode generalises to every teardown path that performs a network write. Whether you are flushing metrics, saving an LLM context window, or writing billing records, the dynamics are identical.&lt;/p&gt;

&lt;p&gt;Anything you write at teardown that exists nowhere else in the system needs a wall-clock budget derived directly from the window you were given.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why do my agent transcripts randomly go missing on call end?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Your persistence logic is likely taking longer than the graceful shutdown window provided by the framework. When the retry loop exceeds this timer, the process is forcefully killed, and the in-memory transcript is destroyed before it can be saved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How long do I have in a shutdown hook before SIGKILL?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It depends entirely on your framework or container orchestrator. You must check the specific graceful shutdown timeout configured in your environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I use a background queue for transcript persistence?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Offloading persistence to a separate queue still requires a network write before the worker process is killed. However, you still have to successfully write the payload to the queue during the shutdown window, so the wall-clock constraint applies to the queue publisher as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does setting my HTTP retry count lower not fix the issue?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A low attempt count still relies on the per-attempt HTTP timeout. If a single HTTP timeout can exceed the framework shutdown window, lowering the attempt count still leaves the write vulnerable to being killed mid-flight.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/bounding-shutdown-retries-by-attempt-count-strands-the-transcript" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/bounding-shutdown-retries-by-attempt-count-strands-the-transcript&lt;/a&gt;&lt;/p&gt;

</description>
      <category>agents</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Agent last sentence is cut off and the room outlives the call</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Sat, 07 Nov 2026 13:34:53 +0000</pubDate>
      <link>https://dev.to/rokasr/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call-9ll</link>
      <guid>https://dev.to/rokasr/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call-9ll</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 10 October 2026.&lt;/p&gt;

&lt;p&gt;A voice agent cutting off its last sentence happens because a fixed sleep cannot predict utterance length, or because the session close call interrupts speech by default. Separately, leaking idle workers occurs when a room delete is cancelled by an outer teardown timeout. Fix both by awaiting speech playout with a six-second cap instead of sleeping. Shield your room deletion from the outer cancellation context and give it its own five-second timeout, treating a not-found response as a success.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The closing line is truncated mid-word when the call ends.&lt;/li&gt;
&lt;li&gt;The longer the goodbye, the more of the audio is lost.&lt;/li&gt;
&lt;li&gt;A cancelled room delete leaves the room active after the transport call finishes.&lt;/li&gt;
&lt;li&gt;A worker remains attached to the orphaned room until the empty room timeout expires.&lt;/li&gt;
&lt;li&gt;This presents as idle workers piling up, which looks like a load problem rather than a resource leak.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;This failure stems from three independent mistakes grouped tightly in the same few lines of teardown code. The transport layer needs to disconnect, the agent needs to finish speaking, and the realtime platform needs to destroy the room. Failing to coordinate them leaves speech truncated or resources orphaned.&lt;/p&gt;

&lt;p&gt;First, using a fixed sleep before hanging up is a crude guess at the length of a variable utterance. If the sleep is too short, it truncates the speech. If it is too long, every call pays for dead air, which bills unnecessarily. The audio pipeline pushes frames into a buffer continuously. A fixed sleep command completely ignores this buffer state.&lt;/p&gt;

&lt;p&gt;Second, the session close call does not drain by default. Calling it while speech is playing interrupts that speech by design. The audio track closes immediately, cutting the stream off regardless of what is still buffered. If you rely on the close call to cleanly wrap up the turn, you lose the end of the sentence every time. The function is designed for a fast exit, not a graceful drain.&lt;/p&gt;

&lt;p&gt;Third, a room delete issued inside a teardown block that the outer timeout is about to cancel is cancelled along with it. Teardown routines usually run inside an enclosing timeout wrapper. If the sequence hits that timeout, the coroutine is cancelled mid-await. The delete operation is cancelled before it can complete. The room is left behind, and the worker sits in it until the platform empty timeout finally sweeps it.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Record the playout wait duration per call, and how often it hits the cap. Expect calls to truncate whenever speech duration exceeds the fixed sleep duration.&lt;/li&gt;
&lt;li&gt;Review the source code for your session close method invocation. Expect the default configuration to interrupt speech rather than waiting for the buffer to drain.&lt;/li&gt;
&lt;li&gt;Pair your room creation and room deletion logs by their room identifier. Expect to find unmatched creations that correlate directly with the idle worker count.&lt;/li&gt;
&lt;li&gt;Count the workers idling in empty rooms. Expect this number to climb exactly when teardown operations time out and cancel the enclosing coroutine.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I replaced the fixed sleep with an explicit await on the current speech playout. The system knows when playback finishes and you do not, so you should never sleep for a duration you can await. I capped this await at 6 s. A capped wait ensures that a wedged synthesizer or an infinitely looping playback routine cannot hold the call open indefinitely.&lt;/p&gt;

&lt;p&gt;To handle the session close, I stopped using the default close method that interrupts speech. Instead, I end the turn by letting the playout finish naturally before tearing down the transport. This allows the caller to hear the entire goodbye before transport teardown.&lt;/p&gt;

&lt;p&gt;For the resource leak, I shielded the room delete from cancellation. Any cleanup that must happen even when the enclosing operation is abandoned has to be shielded from the outer cancellation context. I gave the room delete its own 5 s timeout so it survives the enclosing teardown being cancelled. Without this shield, your cleanup is the first casualty of the timeout it exists to survive.&lt;/p&gt;

&lt;p&gt;Finally, I treat a not-found response on the delete operation as a success. If the room does not exist, someone else having already deleted it is the exact outcome you wanted.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Check if the closing line is statically generated or dynamic. Expect dynamic lines to highlight the truncation more clearly, ruling out a static audio file being genuinely shorter than the fixed sleep.&lt;/li&gt;
&lt;li&gt;Check whether idle workers correlate with teardown cancellations rather than incoming call volume. Expect unmatched room creations and idle workers to spike during outer teardown timeouts, ruling out real traffic load.&lt;/li&gt;
&lt;li&gt;Check the count of workers idling in empty rooms. Expect workers to remain attached to empty rooms until the platform empty timeout expires, confirming a room delete leak rather than process starvation.&lt;/li&gt;
&lt;li&gt;Check whether speech truncation happens on every call or only on utterances longer than the sleep window. Expect immediate truncation whenever session close interrupts active speech, distinguishing default close behavior from an undersized sleep timer.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why guessing utterance length fails
&lt;/h2&gt;

&lt;p&gt;Synthesized speech length is completely unpredictable. Utterance length varies significantly across phrasing and language. Even within the same language, prosody changes and model variance mean the exact same sentence will yield different audio lengths on consecutive runs. Relying on a fixed timer fails in both directions.&lt;/p&gt;

&lt;p&gt;If you set the timer conservatively to avoid truncation, you create a new problem. A fixed sleep that overestimates utterance length forces every call to pay for unnecessary dead air. The caller stays on the line waiting for something else to happen, and you pay your carrier for every second of that silence. If the caller speaks during this dead air, the agent is already tearing down and cannot respond. This leaves the caller talking to a dead line before the hangup eventually fires.&lt;/p&gt;

&lt;p&gt;Awaiting the actual playout event from the audio pipeline is the only correct way to handle this. The underlying media server knows exactly how many frames it has pushed to the transport. By hooking into that completion signal, the application logic stays perfectly synced with the actual audio reality. The 6 s cap acts purely as a safety valve. I record the playout wait duration per call, and how often it hits the cap, to ensure the threshold is high enough to let normal speech finish but low enough to aggressively kill broken sessions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Managing asynchronous cleanup
&lt;/h2&gt;

&lt;p&gt;Teardown code is inherently risky because it executes when the system is already trying to abandon an operation. If the caller hangs up, the transport disconnects, and the system wants to reclaim the worker immediately. However, the room delete still requires an API call to the realtime platform.&lt;/p&gt;

&lt;p&gt;If that API call sits inside the main teardown block, it shares the same timeout. This is exactly where the leak happens. When the timeout fires, Python raises a cancellation error inside the awaitable. The cancellation interrupts the coroutine mid-await, leaving the room active on the platform. The realtime platform never receives the delete instruction, so the room stays open.&lt;/p&gt;

&lt;p&gt;Shielding the cleanup operation decouples it from the parent timeout. By wrapping the room delete in an isolation layer and giving it a dedicated 5 s timeout, you ensure the request completes even if the main teardown fails. It is the same principle of ownership that forces you to place the outbound leg carefully to prevent &lt;a href="https://dev.to/blog/outbound-call-answers-to-dead-air-before-the-agent-joins/"&gt;dead air before the agent joins&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The false load problem
&lt;/h2&gt;

&lt;p&gt;The most confusing part of this failure mode is how it presents on monitoring tools. When a room outlives the call, the worker attached to it has nothing to do. The worker process is still alive and bound to that session.&lt;/p&gt;

&lt;p&gt;Your capacity metrics will show high worker utilization. This looks exactly like a sudden spike in traffic or a legitimate load problem.&lt;/p&gt;

&lt;p&gt;In reality, it is just a leak. The workers are trapped in empty rooms waiting for a server-side empty timeout to finally kick them out. Once you log room creation and room deletion as paired events, the unmatched creations expose the truth. The leak causes a slow buildup of useless capacity that drains your infrastructure budget until the fixed empty timeout provides delayed garbage collection. Counting workers idle in empty rooms gives you the downstream symptom of a failed delete, confirming the leak is active.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling the not-found success state
&lt;/h2&gt;

&lt;p&gt;Treating a not-found response on delete as a success is a critical detail for stable teardown. In a distributed telephony system, multiple actors often try to end the call simultaneously. The caller hangs up their physical phone, sending a BYE over the SIP trunk. The voice agent decides the conversation is over and triggers its own exit. A webhook from the realtime provider fires to indicate the participant left.&lt;/p&gt;

&lt;p&gt;If all three events trigger a room delete, the first one succeeds. The next two receive a not-found error because the room is already gone. If your application code treats this as a failure, it will throw an exception, potentially skipping other crucial local cleanup tasks like releasing a database lock or closing a network socket.&lt;/p&gt;

&lt;p&gt;By swallowing the not-found error and treating it as a successful deletion, you simplify the state machine. Someone else having already deleted the room is exactly the outcome you wanted. The room is gone, you are no longer paying for it, and the worker can terminate cleanly. This allows you to build a system that can absorb duplicate teardown triggers without throwing spurious errors or breaking the local cleanup path. A similar logic applies when an &lt;a href="https://dev.to/blog/voice-agent-end-call-tool-truncates-the-final-sentence-or-loses-the-callers-last/"&gt;end-call tool truncates the final sentence&lt;/a&gt;, where arming a pending closure rather than performing one immediately prevents conflicting operations from breaking the lifecycle.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why does the voice agent cut off the last word of the goodbye?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The teardown logic uses a fixed sleep duration that is shorter than the synthesized audio. When the sleep finishes, the transport disconnects and truncates the audio before the phrase completes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why are there idle workers sitting in empty LiveKit rooms?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A room delete operation was cancelled mid-flight by an enclosing timeout during call teardown. The room stays open until a server-side empty timeout finally sweeps it, keeping the worker attached and idle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How can I safely wait for speech to finish playing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Await the current speech playout event directly from the media buffer instead of using a timer. Cap this await at six seconds so a frozen synthesizer cannot keep the session open forever.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does the session close function interrupt my agent speech?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The default behavior of session close methods is often to drop the active buffer immediately for a fast exit. You must let the playout finish completely before invoking the closure.&lt;/p&gt;

&lt;p&gt;If the boundary this note describes is one you would rather own, &lt;a href="https://dev.to/migration"&gt;the migration scope this sits inside&lt;/a&gt; moves it inside your own infrastructure.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/agent-last-sentence-is-cut-off-and-the-room-outlives-the-call&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sippstn</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Scheduled Outbound Calls Fire An Hour Early After Daylight Saving Transitions</title>
      <dc:creator>Rokas Remeika</dc:creator>
      <pubDate>Thu, 05 Nov 2026 15:03:00 +0000</pubDate>
      <link>https://dev.to/rokasr/scheduled-outbound-calls-fire-an-hour-early-after-daylight-saving-transitions-4jif</link>
      <guid>https://dev.to/rokasr/scheduled-outbound-calls-fire-an-hour-early-after-daylight-saving-transitions-4jif</guid>
      <description>&lt;p&gt;By Rokas Remeika. Published 22 October 2026.&lt;/p&gt;

&lt;p&gt;Scheduling outbound calls using naive local time arithmetic breaks twice a year. A spring-forward gap creates a wall-clock time that does not exist, causing date libraries to throw, while a fall-back overlap creates a time that exists twice, causing unpredictable dialing an hour early. To fix this, ask your date library if a constructed local time is valid to detect gaps, and snap to the next existing instant. For overlaps, consistently select the earlier instant. Finally, validate that the projected call end falls within the calling window using the estimated conversation duration.&lt;/p&gt;

&lt;h2&gt;
  
  
  Symptoms
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;An outbound call goes out at 07:00 local time instead of the expected 08:00 on the Monday following a clock change.&lt;/li&gt;
&lt;li&gt;A scheduled dial executes legally at 19:50, but the conversation is still running at 20:20, pushing past the strict 20:00 cutoff the customer configured.&lt;/li&gt;
&lt;li&gt;A scheduling job throws a runtime exception on a specific date because the underlying date library asserts the constructed local time does not exist.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is actually happening
&lt;/h2&gt;

&lt;p&gt;These present as three separate errors that all look like timezone bugs.&lt;/p&gt;

&lt;p&gt;The first error stems from deriving a timezone exclusively from a phone number's country code. This approach works for most countries, but it is simply wrong for countries that span several zones. Guessing the local time for a contact in a country spanning several zones based purely on the country code is a coin flip. Eventually, your scheduler will guess incorrectly and place a call while the recipient is eating breakfast.&lt;/p&gt;

&lt;p&gt;The second error comes from checking window membership at the start instant only. A calling window constrains the entire conversation rather than the moment of dialing. When you evaluate a scheduled task by comparing the dial instant to the cutoff time, a half-hour call started ten minutes before the cutoff violates the constraint for twenty minutes. The system believes it acted legally because the dispatch cleared the gate, but the recipient experiences an out-of-hours intrusion.&lt;/p&gt;

&lt;p&gt;The third error is raw arithmetic failing across a daylight-saving transition. When calculating future schedules, a spring-forward gap creates a wall-clock time that does not physically exist. A naive local-time construction will immediately throw an exception. Conversely, a fall-back overlap creates a time that exists twice in the same day. Without explicit instructions, date libraries silently pick one of the two instants, usually placing them exactly an hour apart from what you intended. The library makes an arbitrary decision, and your scheduler executes on it.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to confirm it
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Search your application exceptions for invalid date or time errors clustered specifically on the exact day of a spring-forward transition. Expect to see date library validation errors during the spring-forward gap where the target wall-clock time does not exist. This confirms your code is constructing a non-existent wall-clock time and the library is throwing a validation error.&lt;/li&gt;
&lt;li&gt;Query your call logs for the conversation end time against the allowed window cutoff for any complaints about late calls. Expect the start time to be legally inside the window, but the duration pushing the end time past the limit. This confirms the scheduler only validates the dial instant and ignores the call duration.&lt;/li&gt;
&lt;li&gt;Check the timezone assignment logic for multi-timezone regions in your database. Look at a random sample of numbers from multi-zone countries. Expect to find a default offset being blindly applied. This confirms derivations are being made where explicit user selection is required, proving the system is guessing rather than knowing.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;I built my scheduling layer to treat local time complexity as a strict boundary. The first rule I enforce is to refuse to guess. The scheduler derives the country from the parsed phone number and maps that country to an IANA zone only where that mapping is unambiguous. For countries that span multiple zones, I require an explicit selection rather than defaulting. The customer configuring the campaign knows which zone their contact lives in, and I do not. If the explicit selection is missing, the schedule is rejected.&lt;/p&gt;

&lt;p&gt;To enforce the calling window, I require the projected call end to fit entirely inside the allowed window rather than checking only the dial start time. The system calculates the projected end by adding the estimated call duration to the target dispatch time. The scheduler already carries this duration estimate for capacity accounting. When deciding admission inside one transaction, as detailed in /blog/enforcing-maximum-concurrent-sip-calls-without-race-conditions/, the system allocates a slot based on how long the call will occupy it. I feed that same duration metric into the window evaluation. This projection relies on the estimated call duration that the scheduler already tracks for capacity accounting. If the total expected duration pushes the end of the call past the cutoff, the dispatch is declined.&lt;/p&gt;

&lt;p&gt;For daylight-saving transitions, I handle both directions explicitly rather than trusting library defaults. In a spring-forward gap, I detect the missing time by asking the date library whether the constructed local time is valid at all. I use this validity check instead of hardcoding transition dates. When it returns invalid, the system snaps to the next instant that actually exists. In a fall-back ambiguity where the time exists twice, I configure the library to choose the earlier of the two instants consistently. This makes the behavior a documented rule rather than whichever branch the library happens to prefer on a given language version.&lt;/p&gt;

&lt;p&gt;Finally, I instrument every scheduling decision. The scheduler logs the resolved IANA zone and records a boolean flag indicating how it was resolved: explicitly selected or safely derived. I maintain a strict count of gap snaps and ambiguity resolutions, which is the only way you find out your DST handling ran correctly during a transition weekend. I also track a distinct count of dispatches declined specifically because the projected end fell outside the window, separating these rejections from capacity-based delays.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I would check first
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Review how your date library handles ambiguous local times during fall-back overlaps. Expect it to default to one of the two instants silently without warning. Check whether early dispatches happen only during transition hours or persist on standard days to distinguish overlap ambiguity from invalid timezone offsets.&lt;/li&gt;
&lt;li&gt;Inspect the mathematical validation logic for your calling windows. Expect the code to evaluate only the current timestamp against the cutoff limit. If the check lacks an addition of the projected call duration, this rules out complex timezone math errors and confirms a logic gap in your boundary enforcement.&lt;/li&gt;
&lt;li&gt;Look at your timezone mapping dictionary or function for parsed phone numbers. Expect single-zone countries to map cleanly. Correlate out-of-hours complaints with recipient country codes to separate multi-zone derivation errors from daylight saving arithmetic bugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Making daylight saving time an explicit decision
&lt;/h2&gt;

&lt;p&gt;This architecture generalises to any scheduler that acts on someone else's local time. Whether you manage outbound calls, SMS campaigns, appointment reminders, or delivery windows, the local time belongs to the recipient.&lt;/p&gt;

&lt;p&gt;Three rules carry across all these domains. First, never infer a timezone you can ask for. A mapping function is a convenience for single-zone regions, not a replacement for domain knowledge. Second, constrain the end of the activity rather than its start. The user constraint always applies to the entire duration of the intrusion. Third, make both DST directions explicit decisions with a written rule.&lt;/p&gt;

&lt;p&gt;Every mature date library exposes a validity check that doubles as a gap detector. You must use it rather than building a transition calendar. Hardcoding transition dates guarantees your system will fail the moment a local government changes their DST observance policy, which happens frequently. By asking the library if the constructed time is valid, you offload the political complexity to the underlying tz database updates, while your application code safely snaps to the next available instant.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why did a scheduled call dial an hour early on Monday?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Your scheduler performed local-time arithmetic across a fall-back daylight saving transition. Naive local-time arithmetic across the clock change calculated an instant an hour off from the intended local hour.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I handle a scheduled time that does not exist during spring forward?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ask your date library whether the constructed local time is valid instead of hardcoding transition dates. When it returns invalid, snap the scheduled time to the next instant that actually exists.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Should I derive the timezone from the phone number?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Only for countries that do not span multiple timezones, mapping the country to an unambiguous IANA zone. For countries spanning several zones, require an explicit selection instead of defaulting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why did my call run past the calling window cutoff?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Your scheduler checked the window membership using only the dialing start instant. A window constrains the conversation, so you must validate the projected call end using the estimated duration.&lt;/p&gt;

&lt;p&gt;Canonical URL: &lt;a href="https://www.dreamchasers.lt/blog/scheduled-outbound-calls-fire-an-hour-early-after-daylight-saving-transitions" rel="noopener noreferrer"&gt;https://www.dreamchasers.lt/blog/scheduled-outbound-calls-fire-an-hour-early-after-daylight-saving-transitions&lt;/a&gt;&lt;/p&gt;

</description>
      <category>scheduling</category>
      <category>livekit</category>
      <category>voiceai</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
