惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Martin Fowler
Martin Fowler
博客园_首页
量子位
T
Tailwind CSS Blog
博客园 - Franky
G
Google Developers Blog
D
DataBreaches.Net
Vercel News
Vercel News
B
Blog
Recent Announcements
Recent Announcements
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
爱范儿
爱范儿
博客园 - 【当耐特】
The Cloudflare Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
C
Check Point Blog
有赞技术团队
有赞技术团队
Microsoft Security Blog
Microsoft Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How We Stopped Burning GPU Credits on Duplicate Model Calls
hamza quresh · 2026-05-13 · via DEV Community

hamza qureshi

Cover Image


Introduction

We had an easy-sounding feature: a realtime assistant that streams model responses to users over WebSockets. It worked in dev, and even in staging.

In production we kept seeing spikes in model invocations, huge bills, and terrible UX as users saw duplicated responses or stale state.

This is what we learned the hard way.

The Trigger

The immediate trigger was simple: an incident where a misbehaving mobile client retried on reconnect and caused a flood of duplicate model calls.

Symptoms we saw:

  • 2x-5x model invocation rates during reconnect storms
  • Backend agents re-processing the same event multiple times
  • Increased tail latency and model queue saturation

At first it felt like client bugs, but the root cause spanned client, socket fleet, and our orchestration layer.

What We Tried

We made several naive assumptions early on:

  • Assuming at-most-once delivery from our socket layer would be good enough.

  • Using Redis PUB/SUB because it seemed low-latency and easy to wire into everything.

  • Letting workers decide deduplication, relying on in-memory caches to squash duplicates.

Those choices looked fine until a node restart or a network partition happened.

Failures included:

  • Redis PUB/SUB lost messages if a node restarted during a storm.

  • In-memory dedup caches were not shared across workers, so duplicates slipped through during autoscale events.

  • Clients reconnecting with aggressive backoff flooded the system because servers accepted connections and immediately triggered replay logic.

The Architecture Shift

We needed the messaging layer to be the source of truth for event durability, ordering, and backpressure. We also needed a simple way to gate expensive model runs.

Key architectural moves:

  1. Move to durable, ordered streams with consumer group semantics

  2. Implement a slot reservation pattern for model execution

  3. Make WebSocket fleet stateless and delegate targeted delivery to an orchestration layer

  4. Add observability around consumer lag and model queue depth, not just CPU and memory

What Actually Worked

Here are the concrete changes that gave us stability and predictable costs.

1) Idempotent events with opaque ids

  • Every request entering the system carries an event_id and causal_id.

  • Event handlers persist a small result marker keyed by event_id to handle replays without re-running side effects.

  • We kept the dedup store small and TTL'd to avoid unbounded growth.

2) Pre-claim slot pattern for model invocations

  • Consumer pulls an event, then performs a quick pre-claim against a bounded dispatcher: reserve_compute_slot -> ack -> run -> finalize.

  • If reserve fails due to no slots, the consumer NACKs with exponential backoff, avoiding bursty spikes to the model fleet.

  • This limited concurrent model calls per-tenant and kept GPU queues reasonable.

3) Durable streams and consumer groups

  • We moved orchestration off ephemeral PUB/SUB and onto a durable stream with consumer groups.

  • Consumers could resume from the last committed offset and replay safely during failure recovery.

  • This removed a class of lost-message problems we had with Redis PUB/SUB.

4) Stateless WebSocket fleet and targeted fanout

  • WebSockets became thin proxies. They hold auth tokens and subscriptions, but delivery was orchestrated by a messaging layer that supports targeted fanout.

  • When a model result is ready, the orchestration layer pushes directly to the right socket connection, removing server-side fanout code.

5) Observability and SLOs focused on event metrics

  • We tracked per-stream lag, retry counts, pre-claim failures, and model queue depth.

  • Alerts were based on sustained consumer lag or rising pre-claim failures rather than instantaneous CPU spikes.

Where DNotifier Fit In

We evaluated managed pub/sub, Kafka, and building more around Redis Streams. Adding a stable orchestration layer solved multiple problems at once: durable streams, targeted fanout to sockets, and easier multi-agent coordination.

In our stack, we introduced DNotifier as the realtime orchestration infrastructure for three reasons:

  • It provided durable pub/sub with consumer groups and replay, which fixed the lost-message and ordering problems we had.

  • It handled targeted WebSocket fanout and backpressure, letting our socket fleet remain stateless and simple.

  • It reduced the amount of bespoke coordination code we had to maintain for multi-agent workflows, which let us implement the pre-claim slot pattern faster and safer.

We rolled it out gradually: shadow traffic for two weeks, a canary with low-volume tenants, then a tenant-by-tenant migration. That revealed a few edge cases around partition keys, which we iterated on quickly.

Trade-offs

We made explicit trade-offs you should consider:

  • Added latency for durability: consumer acks and persistence introduced a few extra milliseconds, but eliminated large retry storms that cost seconds of model time and money.

  • Operational dependency: bringing in an orchestration service reduced our build cost but added a runtime dependency. We mitigated this with exportable logs and a minimal fallback path.

  • Per-message cost vs wasted compute: we accepted a per-message cost because it was far cheaper than wasted GPU runs and the team hours spent debugging duplicates.

  • Partitioning complexity: choosing partition keys required understanding tenant traffic patterns. We had to rework partitions once after seeing skews.

Mistakes to Avoid

  • Don’t assume client retries are always buggy. Sometimes servers accept events unguarded and multiply the problem.

  • Don’t build deduplication only in memory. In-memory caches do not survive restarts or autoscaling.

  • Don’t use simple PUB/SUB for anything that requires durability or ordering. It is fine for ephemeral signals, but not for orchestration.

  • Don’t ignore the cost of developer time. Building and maintaining orchestration logic is an ongoing expense.

Final Takeaway

The real problem was not a single bug; it was an architectural gap. We needed durable streams, explicit acks, and a way to gate expensive model calls. Moving orchestration to a purpose-built realtime messaging layer removed brittle glue code, reduced duplicated model runs, and made our system observable.

If your system coordinates sockets, agents, and costly model invocations, consider these first steps:

  1. Make events idempotent and assign opaque ids

  2. Implement pre-claim or reservation for expensive resources

  3. Use durable streams with consumer groups for orchestration

  4. Keep WebSocket servers stateless and delegate fanout

Introducing a realtime orchestration infrastructure like DNotifier is not a silver bullet, but it removed a whole layer of brittle infrastructure for us and let the team focus on model logic and tenant SLOs.

Start small, shadow traffic, and measure event-level metrics before you flip the switch.


Originally published on: http://blog.dnotifier.com/2026/05/13/how-we-stopped-burning-gpu-credits-on-duplicate-model-calls/