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

推荐订阅源

Engineering at Meta
Engineering at Meta
酷 壳 – CoolShell
酷 壳 – CoolShell
Forbes - Security
Forbes - Security
S
Schneier on Security
Cyberwarzone
Cyberwarzone
L
Lohrmann on Cybersecurity
NISL@THU
NISL@THU
T
Tenable Blog
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
Schneier on Security
Schneier on Security
K
Kaspersky official blog
AI
AI
Help Net Security
Help Net Security
Hacker News: Ask HN
Hacker News: Ask HN
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threatpost
Attack and Defense Labs
Attack and Defense Labs
I
Intezer
The Cloudflare Blog
博客园 - 叶小钗
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
IT之家
IT之家
Recent Announcements
Recent Announcements
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
宝玉的分享
宝玉的分享
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
O
OpenAI News
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
Microsoft Security Blog
Microsoft Security Blog
B
Blog
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
D
Docker
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
Google Developers Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Designing Resilient Shopify Middleware
Muhammad Mas · 2026-05-09 · via DEV Community

Most Shopify middleware works fine in staging. It breaks in production, during a sale, at 11pm on a Friday.

After auditing dozens of integrations, the failures are almost always the same. Not exotic bugs. Simple architecture decisions made when the system was small and never revisited.

The Pattern That Breaks Everything

Webhook received
  → Direct API call to ERP
    → ERP times out (3s)
      → Shopify retries
        → Duplicate event processed
          → Inventory corrupted
            → Weekend on-call incident

Enter fullscreen mode Exit fullscreen mode

The fix is not a try-catch block. It is replacing the pattern entirely.

  • Rule 1: Acknowledge the webhook in under 200ms. Process it asynchronously.
  • Rule 2: Write state and outbox entries in one transaction. Let a worker handle external calls.
  • Rule 3: Tag every event with an idempotency key before it touches anything.

Reference Architecture

[Shopify]   [ERP]   [WMS]   [Marketplaces]
    |        |       |           |
    v        v       v           v
   ----- API Gateway / Webhook Receiver -----
                     |
              [Message Broker]
                     |
   +-----------------+-----------------+
   |                 |                 |
[Transformer]   [Router]          [Audit Log]
   |                 |
   v                 v
[Domain Services: Orders, Inventory, Customers]
                     |
                     v
              [Outbound Workers]
                     |
                     v
   [Shopify Admin API]   [3rd Party APIs]

Enter fullscreen mode Exit fullscreen mode

Every layer has one job.

  • Webhook receivers do not transform.
  • Transformers do not call APIs.
  • Workers do not own state.

Core Principles Before You Write Any Code

Principle What It Means Why It Matters
Loose coupling Services talk via events, not direct calls One slow service does not block others
Idempotency Same event applied twice = same result Safe to retry without double charges
Backpressure Upstream slows when consumers lag No queue explosions or OOM crashes
Observability Every event is traceable end-to-end You can actually debug incidents
Graceful degradation Non-critical features fail soft Core checkout never goes down

Building Blocks and Their Resilience Role

Component Role Resilience Pattern
API Gateway Receive and validate inbound traffic Rate limiting, schema validation
Webhook Receiver Accept Shopify events Fast 200 ACK, async processing
Message Broker Decouple producers from consumers Durable queues, partitioning
Transformer Map between data formats Pure functions, no side effects
Domain Services Hold canonical state Postgres with row-level locking
Outbound Workers Push updates to external systems Retries, circuit breakers
Audit Log Record every event Append-only, 30-90 day retention

Failure Modes You Must Design For

Failure Mode Trigger Mitigation
Shopify rate limits Burst traffic, bulk updates Token bucket, respect X-Shopify-Shop-Api-Call-Limit
Webhook retry storms Shopify re-delivers for 48h Idempotency keys + dedup table
Network timeouts Flaky third-party API Circuit breaker + exponential backoff
Bad payloads Schema changes upstream Strict validation + dead letter queue
Slow consumers Heavy DB writes Backpressure + queue partitioning
Region outage Vendor failure Multi-region failover + replay logs

The 5 Resilience Patterns That Actually Work

1. Circuit Breaker

Watches error rates on outbound calls. Stops calling a failing service when errors spike above threshold. Gives the dependency time to recover.

CLOSED → (error rate > 50% over 30s) → OPEN
OPEN   → (wait 60s)                  → HALF-OPEN
HALF-OPEN → (3 successful probes)    → CLOSED

Enter fullscreen mode Exit fullscreen mode


2. Exponential Backoff with Jitter

Naive retries create thundering herds. Add jitter to spread the load.

function getBackoffDelay(attempt) {
  const base = Math.min(200 * Math.pow(2, attempt), 60000);
  const jitter = base * 0.2 * Math.random();
  return base + jitter;
}

// attempt 0 → ~200ms
// attempt 1 → ~400ms
// attempt 2 → ~800ms
// attempt 5 → ~6400ms (capped at 60s)

Enter fullscreen mode Exit fullscreen mode


3. Bulkheads

Inventory updates run on a separate worker pool from order pushes. One clogged queue cannot block the other.


4. Timeouts on Everything

// Every outbound call needs a timeout. No exceptions.
const response = await fetch(url, {
  signal: AbortSignal.timeout(5000) // 5s for sync calls
});

Enter fullscreen mode Exit fullscreen mode


5. Dead Letter Queue

After N failed retries, move the event to a DLQ.

  • Alert on growth
  • Replay after fixing root cause
  • Never let a bad event block the main pipeline

Idempotency: The Most Important Property

There is no exactly-once delivery.

There is only:

  • at-least-once delivery
  • plus idempotent consumers
async function processInventoryEvent(event) {
  const alreadyProcessed = await redis.get(`idem:${event.event_id}`);

  if (alreadyProcessed) return; // skip duplicate

  await db.transaction(async (trx) => {
    await trx('inventory')
      .update({ quantity: event.absolute })
      .where({
        sku: event.sku,
        location_id: event.location_id
      });

    await trx('outbox').insert({
      payload: event,
      status: 'pending'
    });
  });

  await redis.setex(
    `idem:${event.event_id}`,
    604800,
    '1'
  ); // 7-day TTL
}

Enter fullscreen mode Exit fullscreen mode


The Outbox Pattern: One Rule That Eliminates Dual-Write Bugs

When you change internal state and need to notify an external system, never do both in the same step.

WITHOUT OUTBOX (dangerous)

1. UPDATE inventory SET quantity = 42
2. POST /shopify/inventory_levels
   (fails? state wrong. success? maybe duplicate)

Enter fullscreen mode Exit fullscreen mode

WITH OUTBOX (safe)

1. BEGIN TRANSACTION
   UPDATE inventory SET quantity = 42
   INSERT INTO outbox (payload, status) VALUES (...)
2. COMMIT
3. Separate worker polls outbox
   → calls Shopify
   → marks row done

Enter fullscreen mode Exit fullscreen mode

If Shopify is slow, the row waits.

If the worker crashes, it restarts and retries.

Internal state is always consistent.


Distributed Shopify Inventory Sync as a Real Example

Step What Middleware Does
1 Receives inventory webhook from Shopify
2 Returns 200 immediately, publishes to broker
3 Transformer converts to canonical event schema
4 Inventory service applies delta with optimistic concurrency
5 Outbox records pending downstream push
6 Worker pushes to ERP, WMS, and marketplace channels
7 Reconciler validates full state every 5 minutes

Observability Baseline

You cannot operate what you cannot see.

Four pillars, from day one:

Pillar Tool Options Key Question Answered
Logs Datadog, ELK, Loki What happened to event X?
Metrics Prometheus, CloudWatch Is queue lag growing?
Traces OpenTelemetry, Jaeger Where did request Y spend time?
Alerts PagerDuty, Opsgenie What needs attention right now?

Metrics that catch the most incidents

  • Queue consumer lag (alert at > 30s)
  • Dead letter queue depth (alert at > 100 unprocessed)
  • Outbound API error rate (alert at > 2%)
  • Webhook 5xx rate (alert at > 0.5%)
  • DB connection pool saturation (alert at > 80%)

Race Condition Handling

Two webhooks for the same SKU arrive at the same millisecond.

Without protection, you lose one.

Option 1: Partition by key (preferred)

Hash SKU to a stream partition.

All events for one SKU process in order on one consumer.


Option 2: Optimistic concurrency

UPDATE inventory
SET quantity = 40,
    version = version + 1
WHERE sku = 'TSHIRT-RED-M'
  AND location_id = 'wh_LA'
  AND version = 7;

Enter fullscreen mode Exit fullscreen mode


Option 3: Distributed locks (last resort)

Serialize via Redis or ZooKeeper.

Works, but adds latency and contention.


Common Mistakes That Cost Merchants Real Money

  • Calling Shopify or ERP APIs directly from webhook handlers
  • Retries with no backoff (thundering herd on every incident)
  • Infinite retries (burns rate limit quota silently)
  • Logs without trace IDs (cannot debug incidents after the fact)
  • No dead letter queue (one bad event blocks the whole pipeline)
  • Ignoring Shopify schema changes in API responses

Build vs Buy

Scenario Recommendation
Simple ERP sync, low volume Use a connector (Celigo, Pipe17)
Custom flows, mid volume Hybrid: connector + custom services
Complex multichannel, high volume Build a custom middleware platform
Regulated industry Build with audit trail baked in

The Full Architecture Guide

This post covers the core patterns.

The full guide on our blog goes deeper with:

  • Complete component-by-component breakdown
  • Database schema design notes
  • Serverless vs container trade-offs
  • REST vs GraphQL decision framework
  • Caching layer design
  • Phased implementation roadmap

👉 Read it here:

Designing Resilient Shopify Middleware


Final Thought

Resilience is not a feature you bolt on later.

It is an architectural property.

The systems that survive Black Friday are usually the systems that were designed to fail safely from day one.