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

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
D
DataBreaches.Net
量子位
C
Cybersecurity and Infrastructure Security Agency CISA
G
Google Developers Blog
小众软件
小众软件
Application and Cybersecurity Blog
Application and Cybersecurity Blog
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cisco Talos Blog
Cisco Talos Blog
P
Proofpoint News Feed
V
Vulnerabilities – Threatpost
Security Latest
Security Latest
T
Tenable Blog
Vercel News
Vercel News
AWS News Blog
AWS News Blog
Forbes - Security
Forbes - Security
M
MIT News - Artificial intelligence
S
Security Affairs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hacker News - Newest:
Hacker News - Newest: "LLM"
美团技术团队
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
Last Week in AI
Last Week in AI
罗磊的独立博客
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
S
Schneier on Security
S
Secure Thoughts
T
Threatpost
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
Y
Y Combinator Blog
F
Full Disclosure
N
Netflix TechBlog - Medium
博客园 - 叶小钗
A
Arctic Wolf
腾讯CDC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
The Exploit Database - CXSecurity.com
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
C
Check Point Blog
C
CERT Recently Published Vulnerability Notes
www.infosecurity-magazine.com
www.infosecurity-magazine.com

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
Dynamic QR Code Redirect Architecture at the Edge
Nacho Gonzál · 2026-04-25 · via DEV Community

A dynamic QR code is a short URL baked into a static image. The "dynamic" part is a database record: a slug-to-destination mapping you can update without reprinting. The image never changes.

Everything interesting happens in the redirect layer. Every scan is a live HTTP request that has to resolve before a user moves on. What follows is what that layer looks like, how to build it right, and where it breaks.

What "dynamic" actually means

The QR image encodes a fixed string like go.yourcompany.com/r/abc123. What changes is the database record mapping abc123 to a destination URL.

The reliability of every printed QR code is exactly equal to the reliability of that redirect server. Nothing in the image acts as a fallback. Slow server = slow scan. Down server = failed scan. Cancelled account = error page. The infrastructure is the product.

The redirect chain

Full sequence from camera tap to destination:

  1. Scan: device reads the QR pattern, decodes the short URL
  2. DNS resolution: resolves the redirect domain to nearest IP (edge) or one fixed IP (single-origin)
  3. TCP + TLS handshake: 50–150ms cold, depending on distance and network
  4. HTTP GET: GET /r/abc123 hits the redirect server
  5. Lookup: server checks cache or KV store for the destination URL mapped to that slug
  6. Async log: queues scan event (timestamp, IP, User-Agent) without blocking the response
  7. HTTP 302: returns Location: <destination>
  8. Browser follows the redirect
  9. Destination loads

Steps 3–7 are what the redirect infrastructure controls. That window is what edge computing compresses.

Single-origin: how most platforms are built

Simplest implementation: one server in Virginia or Frankfurt. Every scan in the world hits that box.

Two problems surface at scale.

Latency first. Sydney to Virginia is about 180ms round-trip just to receive a 200-byte redirect response. On a slow mobile network where TCP setup already costs 100ms, you're at 300ms before the destination even starts loading.

Then there's the single point of failure. A bad deploy, a DDoS, or a data center incident takes every QR code on the platform offline at once. No second region to fail over to.

Most small QR platforms run exactly this. Fine at low volume. Problems show up at scale, and by then codes are already printed.

Edge-first architecture

Edge-first moves redirect logic to globally distributed nodes. Cloudflare Workers and Fastly Compute run JS/Wasm at 200+ cities. DNS resolves via anycast to the nearest edge node.

TTFB for Sydney to nearest edge: 5–20ms instead of 150–200ms.

At the node, the lookup reads from an in-memory cache or distributed KV. Cloudflare Workers KV replicates writes globally within ~60s and reads with single-digit millisecond latency from any node. One KV read, not a database query with joins.

Minimal Cloudflare Worker redirect handler:

export default {
  async fetch(request, env, ctx) {
    const slug = new URL(request.url).pathname.slice(3); // strip /r/
    const destination = await env.REDIRECTS.get(slug);

    if (!destination) {
      return new Response("Not found", { status: 404 });
    }

    // fire-and-forget, doesn't block the redirect
    ctx.waitUntil(logScan(request, slug, env));

    return Response.redirect(destination, 302);
  },
};

async function logScan(request, slug, env) {
  await env.SCAN_QUEUE.send({
    slug,
    ip: request.headers.get("CF-Connecting-IP"),
    country: request.headers.get("CF-IPCountry"),
    ua: request.headers.get("User-Agent"),
    ts: Date.now(),
  });
}

Enter fullscreen mode Exit fullscreen mode

Numbers

Single-origin Edge
TTFB (same region as server) 20–40ms 5–15ms
TTFB (opposite side of world) 150–250ms 15–30ms
P99 under traffic spike 800ms–2s+ 30–60ms
Regional outage 100% of scans fail auto-failover, zero user impact
Cost at scale Vertical scale-out Per-request

302, not 301

Always use 302 (temporary redirect), not 301 (permanent).

301 gets cached aggressively by browsers. If a user previously scanned and their browser cached the old destination, updating the database does nothing; they get the old URL until their cache expires. 302 tells browsers not to cache, so every scan hits the redirect server fresh.

This is the most common redirect architecture mistake. Invisible during testing, only shows up for repeat visitors in production.

Caching at the edge

Not every destination changes frequently. Cache the slug-to-destination mapping at the edge to skip the KV read on hot slugs.

TTL of 30–120s covers most use cases. Fast enough for campaign changes, cheap at scale.

Stale-while-revalidate serves the cached destination immediately and refreshes in the background:

export default {
  async fetch(request, env, ctx) {
    const slug = new URL(request.url).pathname.slice(3);
    const cacheKey = `dest:${slug}`;

    const cached = await env.CACHE.get(cacheKey);
    if (cached) {
      // return immediately, refresh cache in background
      ctx.waitUntil(
        fetchFromOrigin(slug, env).then((dest) =>
          dest ? env.CACHE.put(cacheKey, dest, { expirationTtl: 60 }) : null
        )
      );
      return Response.redirect(cached, 302);
    }

    const destination = await fetchFromOrigin(slug, env);
    if (!destination) return new Response("Not found", { status: 404 });

    ctx.waitUntil(env.CACHE.put(cacheKey, destination, { expirationTtl: 60 }));
    ctx.waitUntil(logScan(request, slug, env));

    return Response.redirect(destination, 302);
  },
};

Enter fullscreen mode Exit fullscreen mode

Users never wait for cache misses. The miss penalty is invisible.

Geo-routing at the edge

Some use cases need different destinations per location. A global brand might send US users to a US landing page and EU users to a different one with localized copy and compliance language. A restaurant chain might send users to the nearest location's menu.

Edge workers get geolocation headers on every request, no external API call needed. On Cloudflare, CF-IPCountry gives you the ISO country code. Store a slug:country key in KV and do the lookup in one read.

export default {
  async fetch(request, env, ctx) {
    const slug = new URL(request.url).pathname.slice(3);
    const country = request.headers.get("CF-IPCountry") ?? "XX";

    // try geo-specific destination first, fall back to default
    const destination =
      (await env.REDIRECTS.get(`${slug}:${country}`)) ??
      (await env.REDIRECTS.get(slug));

    if (!destination) {
      return new Response("Not found", { status: 404 });
    }

    ctx.waitUntil(logScan(request, slug, country, env));
    return Response.redirect(destination, 302);
  },
};

Enter fullscreen mode Exit fullscreen mode

KV key structure:

  • abc123 → default destination
  • abc123:US → US destination
  • abc123:DE → German destination

One KV read for geo-specific, two reads for fallback. Still single-digit millisecond latency, no round-trip to a central routing service.

It's more useful than it looks. Regional A/B tests, localized landing pages, GDPR compliance redirects: all of it becomes a KV write from the dashboard instead of a deploy.

Analytics: async or you're doing it wrong

Writing to a database synchronously before returning the redirect is the worst architecture choice here. It puts a write operation (lock contention, index updates, network round-trip to a central DB) directly in the hot path of every single scan.

Two patterns that work:

Queue-based: the Worker sends a lightweight event to Cloudflare Queues or SQS and returns the redirect immediately. A separate consumer drains the queue, enriches events with geo-lookup and device parsing, and writes to the analytics store. If the pipeline backs up or errors, scans keep working.

Edge streaming: log events go to Cloudflare Logpush, then object storage, then Kafka or Kinesis, then the analytics DB in batches. More infrastructure, but scales to millions of scans per day without per-event writes.

Same principle either way: redirect response latency stays fixed. Analytics write latency is irrelevant to users.

What to monitor in production

A redirect service has a short list of things worth tracking.

Redirect TTFB by region: track P95 and P99, not average. Average hides tail latency that shows up for users on slow mobile networks. If P99 in Asia spikes to 800ms, something is wrong with KV replication or a regional node.

Cache hit rate: a sudden drop means something invalidated the edge cache. Catch it before it becomes a latency regression.

Scan error rate: 404s are expected for deleted slugs. 500s, timeouts, and connection resets need alerting. One bad deploy should not silently fail millions of scans.

Queue depth: if the scan event queue is backing up, the analytics pipeline has a problem. The redirect still works, but lag accumulates. Left long enough, you'll either drop events or overwhelm the consumer when it catches up.

In Cloudflare Workers, Workers Analytics Engine is a time-series store built for this pattern. Push a data point per request, query with SQL-like syntax via the Analytics Engine API.

// inside fetch handler, non-blocking
ctx.waitUntil(
  env.ANALYTICS.writeDataPoint({
    blobs: [slug, country, request.headers.get("CF-Ray") ?? ""],
    doubles: [Date.now()],
    indexes: [slug],
  })
);

Enter fullscreen mode Exit fullscreen mode

Query it later:

SELECT
  blob1 AS slug,
  blob2 AS country,
  count() AS scans,
  quantilesMerge(0.95)(quantilesState(0.95)(double1)) AS p95_ts
FROM SCAN_EVENTS
WHERE timestamp > NOW() - INTERVAL '1' HOUR
GROUP BY slug, country
ORDER BY scans DESC

Enter fullscreen mode Exit fullscreen mode

One endpoint. No external observability stack in the hot path.

Failover

When a node goes unhealthy, anycast DNS shifts requests to the next-nearest healthy one automatically. Latency ticks up slightly; the service stays up. With single-origin, one failure is a complete outage.

The resilience pattern most people skip: stale-on-error. If the origin data store is unreachable, serve the last-cached destination instead of returning an error. Destination changes are rare; the cached value is almost always right. A slightly stale redirect beats an error page every time.

The part that's not a performance problem

The short URL encoded in a printed QR code is permanent. Once it's on packaging, signage, or business cards, you can't change it without reprinting.

If that URL is qrtiger.io/r/abc123, every printed code's operational status is permanently tied to QR Tiger. Cancel the subscription and you get error pages. Platform shuts down, error pages. Price increase, you negotiate from zero leverage.

Owning the redirect domain fixes this. go.yourcompany.com/r/abc123 can point at any infrastructure at any time. Update a DNS record to switch platforms or self-host. The printed codes never change; what's behind them does.

Most QR platforms charge a premium for custom domains or don't support them at all. That's not incidental. A platform hosting your redirect domain has permanent leverage over materials that cost real money to replace.

Build vs. buy

A self-hosted redirect on Cloudflare Workers costs about $5/month for the Workers subscription plus under $0.50/million redirect reads. The Worker is 50–100 lines. A few hours to deploy.

What a platform adds: destination management UI, analytics dashboard, QR generation tooling, reliability guarantees. For teams without dedicated infra engineers, that management layer is the actual product. That's probably why most teams should buy rather than build.

Either way: edge compute for the redirect hop, analytics out of the hot path, short-TTL caching with stale-while-revalidate, stale-on-error resilience, and a redirect domain you control.

The QR image is just the entry point. The redirect layer is the product.


I'm building QR Nova, a QR platform built on this architecture. Happy to answer questions in the comments.