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

推荐订阅源

V
V2EX
博客园 - 叶小钗
Last Week in AI
Last Week in AI
Google DeepMind News
Google DeepMind News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
P
Proofpoint News Feed
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
aimingoo的专栏
aimingoo的专栏
月光博客
月光博客
量子位
A
About on SuperTechFans
Engineering at Meta
Engineering at Meta
Apple Machine Learning Research
Apple Machine Learning Research
Jina AI
Jina AI
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
博客园_首页
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Stack Overflow Blog
Stack Overflow 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
Why your Sentry events never reach your serverless functions
Michel Faure · 2026-05-10 · via DEV Community

Comic strip 4 panels — Panel 1

The morning Sentry lied to me, in the wrong direction

A Tuesday morning in mid-April, I open the cron digest of Rembrandt, the ERP I've been coding alone for L'Atelier Palissy. The day before, I had finally wrapped four critical crons with Sentry.withMonitor to get readable SLOs, and I was waiting for that first digest like a Sunday morning of league results. The board is red. 41 timeouts on sync-formidable over five hours, 9 on check-replies, 1 on sync-pennylane, and a 5xx API SLO firing for good measure. I sit down.

Niran, the twenty-year-old intern who spends his Saturdays at the dojo and his weeks in a dark hoodie, is already at his desk, soda can next to the laptop. He glances at my screen, glances at Supabase Studio, and drops without looking up: "Yesterday's leads are in the database." They are. Inserts into contacts happened, the lead-pipeline tasks ran, the Slack notifications went out. The cron did its job. What Sentry is telling me is the opposite of what the database confirms — an instrument lying to me, forcing me to understand the instrument before touching the code.

Serverless shutdown and the buffer that never leaves

Sentry.withMonitor(slug, fn, config) is a clean sandwich on paper. It sends an in_progress check-in at startup, runs fn, and sends an ok or error check-in on the way out. As long as the process lives long enough for both check-ins to actually be flushed, the monitor reflects reality. The trap starts where your function lives.

On Vercel, a route is a lambda. The runtime freezes the worker as soon as the handler returns — or more precisely, as soon as the runtime considers the HTTP response to be on its way. The Sentry transport, however, is asynchronous by design: events are placed in an in-memory buffer, which a background worker pushes to the ingest endpoint. If the worker hasn't had its window, the buffer dies with the lambda. The in_progress check-in had already gone out during execution; the final ok never did. Sentry sees a cron that started and never replied, waits maxRuntime, and declares the monitor timed out.

This is the exact signature of the silent inverted bug: your code works, your observability lies in the direction of a false alert, and you're going to lose a day verifying what's wrong before admitting that what's wrong is the observability itself.

The correct pattern, in lib/sentry-monitors.ts

The rule fits in five lines. await Sentry.flush(2000) in a finally, around the Sentry.withMonitor call. The flush forces the buffer to drain before the lambda hands control back, with a two-second timeout so it doesn't push you past Vercel's maxDuration if the Sentry network coughs.

// lib/sentry-monitors.ts
export async function withCronMonitor<T>(
  slug: string,
  config: CronConfig,
  fn: () => Promise<T>,
): Promise<T> {
  if (!process.env.SENTRY_DSN) return fn()

  try {
    return await Sentry.withMonitor(slug, fn, {
      schedule: { type: 'crontab', value: config.schedule },
      checkinMargin: config.checkinMargin ?? 5,
      maxRuntime: config.maxRuntime ?? 30,
      timezone: config.timezone ?? 'Etc/UTC',
      failureIssueThreshold: 1,
      recoveryThreshold: 1,
    })
  } finally {
    // Serverless: force the ok/error check-in flush before the lambda is
    // frozen. Without this, Sentry never sends the second check-in and
    // declares a timeout after maxRuntime.
    try {
      await Sentry.flush(2000)
    } catch (flushErr) {
      console.warn('[sentry-monitors] flush failed:', flushErr)
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

The try/catch around flush isn't an excess of caution. It's the wrapper's most important invariant: a failed Sentry connection must never block the cron itself. You observe, you don't intercede. If the instrument falls, the business goes through.

The handler-side call stays sober — the wrapper carries the entire mechanism:

// app/api/cron/sync-formidable/route.ts
export async function GET(request: NextRequest) {
  return withCronMonitor(
    'sync-formidable',
    CRON_CONFIGS['sync-formidable'],
    () => handleSync(request),
  )
}

Enter fullscreen mode Exit fullscreen mode

There's another consistency you only discover the day it's missing: Vercel's maxDuration must be strictly lower than Sentry's maxRuntime. If the lambda is killed by SIGTERM before reaching the finally, the flush doesn't even get a chance to fail — it's never called. On sync-formidable, this surfaced later as a second incident (TEF-ERP-2, commit 2282dd9) where a slow WordPress request was pushing past Vercel's 60 s ceiling. We added an AbortSignal.timeout(8_000) per fetch to guarantee the finally is always reached.

The rule extends to any short serverless function emitting Sentry events

The trap isn't reserved for crons. It lives in any serverless function short enough that the lambda is frozen before the Sentry worker drains. Rarely-called webhooks, utility API routes, OAuth callbacks, an instrumented healthcheck route — anywhere you depend on an event that should go out but doesn't get the time to leave the buffer. The generic rule fits in one sentence: any serverless route that produces Sentry events ends its path with an await Sentry.flush(2000) in a finally, no exceptions. It's the observability-side echo of the well-known business-side rule: await everything that must complete before the return, because in serverless, return means die.

Coda

Four weeks after that red Tuesday, the morning digest has become a calm object. ok check-ins arrive, error check-ins arrive when they should, and the SLOs reflect what the database says. Five finally lines brought back into view incidents that had been slipping out of my field of vision since the very first wrap, and they taught me something larger: an observability system that hasn't been tested in the exact conditions of its runtime — cold start, lambda freeze, asynchronous transport — observes nothing, it makes things up. The truly critical cron is the one that flushes.


Companion code: rembrandt-samples/sentry-cron-flush-serverless/ — flush pattern + Vercel cron handler example, MIT.