選項
首頁首頁 Skill 雲端基礎設施 sentry-architecture-variants

適用於不同應用程式類型的 Sentry 架構模式。在為單體應用程式、微服務、無伺服器或混合式架構設定 Sentry 時請參考這些模式。可透過「sentry 單體式架構設定」、「sentry 微服務」、「sentry 無伺服器架構」、「sentry 架構模式」等短語觸發。

...展開全部
50
更新時間 2026-06-29

關於sentry-architecture-variants

「sentry-architecture-variants 」技能旨在簡化 Sentry 在各種應用程式架構中的設定與配置流程。它能簡化在不同類型系統(包括單體式、微服務、無伺服器及混合式架構)中部署 Sentry 的流程。 此技能可自動完成專案結構、追蹤、租戶隔離及團隊存取控制等關鍵功能的設定,確保 Sentry 配置符合特定架構的需求。透過自動化這些任務,此技能不僅能減少所需的手動操作,更能加速在複雜環境中部署 Sentry。

此技能的主要功能包括為每種架構建立量身打造的 Sentry 配置,其中包含為微服務、無伺服器應用程式及混合系統設定分散式追蹤。 此技能亦支援邊緣函式監控、訊息佇列追蹤上下文傳播,以及基於團隊的存取控制。它確保專案結構與應用程式的拓撲結構相符,並能輕鬆管理不同元件間的存取權限與追蹤。這種全面性的方法可確保 Sentry 配置得當,能有效監控與管理錯誤回報及效能監控。

「sentry-architecture-variants 」技能非常適合負責在使用各種架構的應用程式中設定和維護 Sentry 的團隊。 對於從事單體應用程式、微服務或混合雲系統開發的 DevOps 人員、系統管理員及工程師而言,此技能極具實用價值。此技能有助於簡化 Sentry 的設定流程,並確保監控工具已正確配置,以滿足各類應用程式的獨特需求,從集中式配置到包含多項服務與租戶的複雜分散式系統皆能涵蓋。

常見問題

如何觸發此技能?

您可以透過「sentry monolith setup」、「sentry microservices」、「sentry serverless」或「sentry architecture pattern」等短語來觸發此技能。

這項技能是否相容於所有應用程式類型?

是的,此技能專為單體架構、微服務、無伺服器及混合式架構設計。

使用此技能有哪些先決條件?

在使用此技能之前,請確保您的應用程式架構已建立文件紀錄、擁有服務清單、已定義團隊負責範圍,並充分理解部署模式。

這項技能是否支援多租戶應用程式?

是的,此技能具備為多租戶應用程式新增租戶隔離標籤的功能。

使用此技能需要哪些工具?

此技能需要以下工具:Read、Write、Edit 及 Grep。

在 GitHub 上查看

Sentry Architecture Variants

Overview

Choose the right Sentry SDK, project layout, and tracing strategy for eachapplication architecture. Every pattern below uses Sentry SDK v8 APIs —@sentry/node, @sentry/browser, @sentry/react, @sentry/react-native,@sentry/aws-serverless, and @sentry/google-cloud-serverless. The goal isone coherent trace from the user's device through every backend hop, regardlessof how many runtimes or deployment targets sit in between.

Deep-dive references for each pattern:Monolith |Microservices |Serverless |Event-driven |Frontend SPA |Mobile |Hybrid |Errors

Prerequisites

  • Node.js 18+ (or target platform runtime)
  • Sentry organization with at least one project created at sentry.io
  • SENTRY_DSN available as an environment variable (one per Sentry project)
  • Application architecture documented — service inventory, deployment targets, team ownership mapped
  • For distributed tracing: all inter-service transports identified (HTTP, gRPC, Kafka, SQS)

Instructions

Step 1 — Identify Your Architecture and Select SDK Packages

Map every runtime in your system to the correct Sentry SDK package and project layout.

ArchitectureSDK PackageSentry ProjectsKey Integration
Monolith@sentry/node1 project, env tagsModule tags + ownership rules
Microservices@sentry/node (per service)1 project per serviceDistributed tracing via headers
Serverless (Lambda)@sentry/aws-serverless1 per function groupSentry.wrapHandler() + auto-flush
Serverless (GCP)@sentry/google-cloud-serverless1 per function groupSentry.wrapCloudEventFunction()
Event-driven (Kafka/SQS)@sentry/node1 per consumer groupcontinueTrace() from message headers
Frontend SPA@sentry/browser or @sentry/react1 frontend projectbrowserTracingIntegration()
Mobile (React Native)@sentry/react-native1 mobile projectNative crash reporting + JS errors
HybridMix of above1 per deployment targetCross-platform trace correlation

Install the SDK for your architecture:

# Monolith / Microservices / Event-drivennpm install @sentry/node @sentry/profiling-node# Serverless — AWS Lambdanpm install @sentry/aws-serverless# Serverless — Google Cloud Functionsnpm install @sentry/google-cloud-serverless# Frontend SPA (React)npm install @sentry/react# Mobile — React Nativenpx @sentry/wizard@latest -i reactNative

Step 2 — Initialize Sentry for Each Architecture Pattern

Monolith — Single Project, Module Tags

One DSN, one project. Separate concerns with module tags and team ownership rules.

// instrument.mjs — load via: node --import ./instrument.mjs app.jsimport * as Sentry from '@sentry/node';Sentry.init({  dsn: process.env.SENTRY_DSN,  environment: process.env.NODE_ENV,  release: process.env.APP_VERSION,  tracesSampleRate: 0.1,  initialScope: { tags: { app: 'monolith' } },});// Tag errors by module so each team sees only their issuesfunction captureModuleError(module: string, error: Error) {  Sentry.withScope((scope) => {    scope.setTag('module', module);    scope.setTag('team', getTeamForModule(module));    Sentry.captureException(error);  });}// Module-based breadcrumbs for traceabilitySentry.addBreadcrumb({ category: 'auth', message: 'Login attempt', level: 'info' });captureModuleError('auth', new Error('Token expired'));// Dashboard ownership: tags.module:auth → #platform-team

Microservices — Project-per-Service, Distributed Tracing

Each service gets its own Sentry project. A shared config package keeps init consistent.

// packages/sentry-config/index.ts — shared across all servicesimport * as Sentry from '@sentry/node';export function initServiceSentry(serviceName: string) {  Sentry.init({    dsn: process.env.SENTRY_DSN,    environment: process.env.NODE_ENV,    release: `${serviceName}@${process.env.APP_VERSION}`,    serverName: serviceName,    tracesSampleRate: 0.1,    sendDefaultPii: false,    initialScope: {      tags: {        service: serviceName,        cluster: process.env.K8S_CLUSTER || 'default',        namespace: process.env.K8S_NAMESPACE || 'default',      },    },  });}// Usage: initServiceSentry('api-gateway');

HTTP tracing works automatically — SDK v8 propagates sentry-trace and baggage headers on all outbound HTTP requests. For service mesh (Istio/Linkerd), headers pass through transparently. For non-HTTP transports (gRPC, message queues), see event-driven pattern below and microservices deep-dive.

Serverless — Lambda and Cloud Functions

Serverless SDKs wrap your handler to auto-capture errors and flush events before the runtime freezes.

// AWS Lambda — handler.tsimport * as Sentry from '@sentry/aws-serverless';Sentry.init({  dsn: process.env.SENTRY_DSN,  environment: process.env.STAGE,  tracesSampleRate: 0.1,});export const handler = Sentry.wrapHandler(async (event, context) => {  Sentry.setTag('function', context.functionName);  Sentry.setTag('region', process.env.AWS_REGION);  // Track cold starts  const isColdStart = !global.__sentryWarm;  global.__sentryWarm = true;  Sentry.setTag('cold_start', String(isColdStart));  const result = await processRequest(event);  return { statusCode: 200, body: JSON.stringify(result) };});// wrapHandler auto-calls flush() — do NOT call it yourself (double-flush causes timeout)
// Google Cloud Functions — index.tsimport * as Sentry from '@sentry/google-cloud-serverless';Sentry.init({ dsn: process.env.SENTRY_DSN, tracesSampleRate: 0.1 });export const httpHandler = Sentry.wrapHttpFunction(async (req, res) => {  res.json(await processRequest(req.body));});export const eventHandler = Sentry.wrapCloudEventFunction(async (event) => {  await processEvent(event.data);});

Event-Driven — Kafka, SQS, and Message Queues

Propagate trace context through message headers so consumer spans connect to producer traces.

import * as Sentry from '@sentry/node';// Producer: embed trace context in message headersasync function publishToKafka(topic: string, payload: object) {  const activeSpan = Sentry.getActiveSpan();  const headers: Record<string, string> = {};  if (activeSpan) {    headers['sentry-trace'] = Sentry.spanToTraceHeader(activeSpan);    headers['baggage'] = Sentry.spanToBaggageHeader(activeSpan) || '';  }  await Sentry.startSpan(    { name: `kafka.produce.${topic}`, op: 'queue.publish' },    () => kafka.send({ topic, messages: [{ value: JSON.stringify(payload), headers }] })  );}// Consumer: continue the producer's traceasync function consumeFromKafka(message: KafkaMessage) {  const headers = message.headers || {};  Sentry.continueTrace(    {      sentryTrace: headers['sentry-trace']?.toString(), // Buffer → string      baggage: headers['baggage']?.toString(),    },    () => {      Sentry.startSpan(        { name: `kafka.consume.${message.topic}`, op: 'queue.process' },        async (span) => {          try {            await processMessage(message);            span.setStatus({ code: 1 });          } catch (error) {            span.setStatus({ code: 2, message: 'consumer_error' });            Sentry.captureException(error);            throw error;          }        }      );    }  );}

For SQS consumers on Lambda, see event-driven deep-dive.

Frontend SPA — Browser and React

import * as Sentry from '@sentry/react';Sentry.init({  dsn: process.env.REACT_APP_SENTRY_DSN,  release: process.env.REACT_APP_VERSION,  tracesSampleRate: 0.1,  replaysOnErrorSampleRate: 1.0,  integrations: [    Sentry.browserTracingIntegration(),    Sentry.replayIntegration({ maskAllText: true, blockAllMedia: true }),  ],  // Must match your API domain or frontend-to-backend traces break  tracePropagationTargets: ['localhost', /^https:\/\/api\.yourapp\.com/],});

Route-based transactions, error boundaries, and session replay configuration: see frontend SPA deep-dive.

Mobile — React Native

import * as Sentry from '@sentry/react-native';Sentry.init({  dsn: process.env.SENTRY_DSN,  tracesSampleRate: 0.2,  integrations: [    Sentry.reactNativeTracingIntegration({      routingInstrumentation: Sentry.reactNavigationIntegration(),    }),  ],  tracePropagationTargets: [/^https:\/\/api\.yourapp\.com/],  enableNativeCrashHandling: true,  attachScreenshot: true,  attachViewHierarchy: true,});export default Sentry.wrap(App);// Upload source maps + dSYMs in CI — see mobile deep-dive

Full navigation instrumentation and CI upload commands: see mobile deep-dive.

Step 3 — Wire Up Hybrid and Cross-Platform Tracing

For systems that span multiple architectures, connect traces end-to-end. The trace flow for a typical hybrid system:

  1. @sentry/react creates a transaction on user click
  2. Browser SDK adds sentry-trace + baggage headers to fetch()
  3. API gateway (@sentry/node) auto-continues the trace
  4. API gateway calls payment-service — headers propagate via HTTP
  5. payment-service publishes to Kafka — headers injected manually (see event-driven pattern)
  6. Worker (@sentry/node) continues trace from Kafka headers

Result: single trace ID visible across all services in Sentry Trace View. Backend-to-frontend correlation requires tracePropagationTargets in the browser SDK matching your API domains. Without this, the browser SDK will not attach trace headers and traces break at the browser-to-server boundary. See hybrid deep-dive.

Architecture decision matrix:

ArchitectureProjectsTracing StrategySDK FlushKey Gotcha
Monolith1Single-service spansAutomaticModule tag cardinality — keep under 50
Microservices1 per serviceDistributed via HTTP headersAutomaticMissing baggage breaks sampling
Serverless1 per function groupPer-invocation, auto-flushwrapHandler()Double-flush causes timeout
Event-driven1 per consumer groupcontinueTrace() from headersManual periodicDLQ needs separate error capture
Frontend SPA1browserTracingIntegration()Automatic (beacon)tracePropagationTargets required
Mobile1reactNativeTracingIntegration()AutomaticSource maps + dSYMs required
HybridMix of aboveEnd-to-end header propagationPer-componentOne missing link breaks whole trace

Output

After applying the appropriate pattern, you will have:

  • Architecture-specific Sentry.init() configuration with correct SDK package
  • Distributed tracing connected across all services (HTTP, gRPC, and message queues)
  • Serverless handlers wrapped with automatic error capture and event flushing
  • Event-driven consumers that continue producer traces via message headers
  • Frontend SPA with route-based transactions, session replay, and backend trace correlation
  • Mobile app with native crash reporting, screenshot capture, and navigation tracing
  • Hybrid systems with end-to-end trace visibility from browser/mobile through every backend hop

Error Handling

ErrorCauseSolution
Distributed traces brokenMissing header propagationVerify sentry-trace AND baggage headers in every inter-service call
Lambda events lost after timeoutCalling flush() inside wrapHandlerRemove manual flush()wrapHandler auto-flushes
Kafka consumer traces disconnectedHeaders not serialized as stringsCall .toString() on Kafka message headers before continueTrace()
SPA traces stop at API boundarytracePropagationTargets missingAdd API domain regex to browser SDK init
React Native traces unreadableMissing source maps / dSYMsRun sentry-cli sourcemaps upload and sentry-cli upload-dif in CI
Multi-tenant data leakagesetTag() at global scopeUse withScope() per request — global tags persist across requests
Worker events silently droppedNo periodic flushAdd setInterval(() => Sentry.flush(2000), 30_000)
High cardinality alertDynamic values in span namesUse parameterized names: kafka.consume.orders not kafka.consume.order-12345

See also: Full error reference

Examples

Example 1 — Monolith with 5 teams:Request: "Set up Sentry for a monolith with auth, billing, inventory, shipping, and analytics modules."Result: Single Sentry project with module and team tags. Each team filters issues via tags.module:billing. Ownership rules route alerts to the correct Slack channel.

Example 2 — Microservices with Kafka:Request: "Configure Sentry for 12 microservices communicating via REST and Kafka."Result: 12 Sentry projects with shared initServiceSentry(). HTTP traces auto-propagate. Kafka producers inject sentry-trace/baggage into headers. Consumers call continueTrace(). Trace view: api-gateway -> order-service -> [kafka] -> fulfillment-worker.

Example 3 — Serverless API on Lambda:Request: "Add Sentry to 8 AWS Lambda functions behind API Gateway."Result: One Sentry project. Each handler wrapped with Sentry.wrapHandler(). Cold starts tagged. No manual flush() calls.

Example 4 — React SPA + Node API:Request: "Full-stack Sentry for a React frontend calling a Node.js Express API."Result: Two projects (frontend + backend). React uses @sentry/react with browserTracingIntegration() and replayIntegration(). tracePropagationTargets connects frontend to backend traces.

See also: Full examples

Resources

  • Node.js SDK Guide
  • AWS Lambda Guide
  • Google Cloud Functions Guide
  • React SDK Guide
  • React Native SDK Guide
  • Distributed Tracing
  • Session Replay
  • Performance Monitoring

Next Steps

  • Run the sentry-performance-tuning skill to optimize tracesSampleRate and tracesSampler for production traffic volumes
  • Use sentry-cost-tuning to set rate limits and event budgets per project
  • Configure sentry-deploy-integration to tie releases to deploys for regression detection
  • Set up sentry-multi-env-setup to manage DSN routing across staging/production
  • Apply sentry-reliability-patterns for retry logic and circuit breakers around Sentry calls

所有檔案

1 個檔案

安裝 sentry-architecture-variants

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/jeremylongshore/claude-code-plugins-plus-skills/blob/main/plugins/saas-packs/sentry-pack/skills/sentry-architecture-variants/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/,Claude 會自動偵測並使用該技能

相關技能

Cloudflare Manager
更新時間 2026-06-29
pinecone
更新時間 2026-06-29
azure-setup-guide
更新時間 2026-06-29
cloud
更新時間 2026-06-29
OR