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

推荐订阅源

U
Unit 42
Vercel News
Vercel News
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
量子位
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)

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
I kept improving my .NET order pipeline after a CTO left ...
Aftab Bashir · 2026-05-24 · via DEV Community

A few weeks ago I published an article about an event-driven order pipeline I built in .NET. A CTO named Andrew Tan left a comment pointing out that my outbox pattern had a gap - the polling interval was trading latency for database load, and I had no protection against multiple poller instances stepping on each other.

I fixed the outbox gap in a follow-up post. But Andrew also flagged two more things worth addressing. This is where the pipeline stands now after working through all of them.

Where we started

The original pipeline had a working outbox pattern. Orders and outbox records written in the same PostgreSQL transaction. A background service polling every 5 seconds and publishing to Kafka. Messages marked as processed after a successful publish.

It worked. But it had three gaps Andrew spotted:

  1. No protection for horizontal scaling - two poller instances would grab the same message
  2. No backoff when Kafka was down - just constant retrying every 5 seconds
  3. No dead letter path - messages that failed repeatedly just sat there forever

Fix 1 - FOR UPDATE SKIP LOCKED

The original query just fetched unprocessed messages. If you ran two instances of the service, both would grab the same messages and try to publish them twice.

The fix is a raw SQL query with FOR UPDATE SKIP LOCKED:

SELECT * FROM "OutboxMessages"
WHERE "Processed" = false AND "RetryCount" < 3
ORDER BY "CreatedAt"
FOR UPDATE SKIP LOCKED

Enter fullscreen mode Exit fullscreen mode

FOR UPDATE locks the rows for the duration of the transaction. SKIP LOCKED means any other poller instance skips rows that are already locked rather than waiting. Two instances running in parallel will never claim the same message. Scale horizontally as much as you want.

The transaction stays open across the entire fetch, process, and save cycle. Only when the message is marked as processed and the transaction commits do the locks release.

Fix 2 - Exponential backoff for Kafka failures

The original service retried every 5 seconds regardless of what was happening. If Kafka was down, it would hammer the broker with connection attempts at a fixed rate.

The updated service tracks whether any publish failed and adjusts the wait interval accordingly:

if (anyKafkaFailure)
{
    _logger.LogWarning("Kafka publish failed. Backing off for {Seconds}s", _currentBackoff);
    await Task.Delay(TimeSpan.FromSeconds(_currentBackoff), stoppingToken);
    _currentBackoff = Math.Min(_currentBackoff * 2, MaxBackoffSeconds);
}
else
{
    _currentBackoff = BaseBackoffSeconds;
    await Task.Delay(TimeSpan.FromSeconds(BaseBackoffSeconds), stoppingToken);
}

Enter fullscreen mode Exit fullscreen mode

First failure waits 5 seconds, then 10, then 20, then caps at 60. Any successful publish resets to 5 seconds. The service backs off gracefully when Kafka is struggling instead of making things worse.

Bad payloads that fail to deserialize increment the retry count but do not trigger backoff - only Kafka connection failures do. That distinction matters because you do not want a single corrupt message to slow down processing of everything else.

Fix 3 - Dead letter path

The original implementation stopped retrying after 3 attempts and left the message sitting in the outbox with RetryCount = 3. It was effectively dead but invisible.

Now when a message hits the retry limit, it moves to a DeadLetterMessages table:

if (message.RetryCount >= MaxRetries)
{
    var deadLetter = new DeadLetterMessage
    {
        OrderId = message.OrderId,
        EventType = message.EventType,
        Payload = message.Payload,
        OriginalCreatedAt = message.CreatedAt,
        DeadLetteredAt = DateTime.UtcNow,
        FailureReason = message.Error ?? "Max retries exceeded",
        RetryCount = message.RetryCount
    };

    context.DeadLetterMessages.Add(deadLetter);
    context.OutboxMessages.Remove(message);

    _logger.LogWarning(
        "Message {MessageId} for order {OrderId} moved to dead letter after {RetryCount} retries",
        message.Id, message.OrderId, message.RetryCount);
}

Enter fullscreen mode Exit fullscreen mode

The outbox stays clean. Dead messages go somewhere visible. There is also a GET /api/deadletters endpoint so operators can inspect what failed and why without touching the database directly.

What the full picture looks like now

The outbox processor now handles four scenarios cleanly:

Happy path - message fetched, published to Kafka, marked as processed. Next poll in 5 seconds.

Kafka is down - publish fails, retry count increments, backoff doubles. Service waits progressively longer and tries again when Kafka recovers.

Multiple instances - FOR UPDATE SKIP LOCKED ensures each message is claimed by exactly one instance. No duplicate publishes.

Persistent failure - after 3 retries, message moves to dead letters. Outbox stays clean. Operator can inspect and replay manually.

The honest reflection

None of these improvements would have happened without Andrew's comment. The original implementation worked in testing. All three gaps only show up under specific production conditions - horizontal scaling, broker failures, persistent bad messages.

This is why public code review matters. A fresh pair of eyes from someone who has hit these problems before is worth more than any amount of solo review.

Source code: github.com/aftabkh4n/order-pipeline

If you are building event-driven systems this is worth reading alongside the original article. The outbox pattern is the foundation. These three additions are what make it production-ready.