The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
backend: bound ingest concurrency with admission gate (503 + Retry-After on saturation)
jstojiljkovic14b4aa6e1759
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8cbddeb0..324643c4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -257,6 +257,10 @@ DUCKDB_MEMORY_LIMIT= # e.g. 4GB. Unset = DuckDB auto-tunes (~80DUCKDB_THREADS= # e.g. 4. Unset = DuckDB auto-tunes (= cores). Cap in constrained/shared environments.DUCKDB_CHECKPOINT_THRESHOLD= # e.g. 256MB. Unset = DuckDB default (16MB). Raise under sustained ingest to reduce WAL checkpoint stalls; costs a larger WAL and longer restart replay.+# Ingest admission gate (all telemetry ingest endpoints: /api/report, /api/profiles/ingest, /api/otel/*)+INGEST_MAX_CONCURRENT= # max concurrently processed ingest requests. Unset = 2×CPU cores, min 4. Bounds ingest memory so overload sheds load with 503s instead of the process being OOM-killed (on DuckDB an OOM death is followed by a minutes-long WAL-replay stall on restart).+INGEST_ADMISSION_WAIT_SECONDS=5 # how long a request may wait for a slot before the 503 + Retry-After; 0 = reject immediately when saturated+# NotificationsNOTIFICATION_POLL_SECONDS=60 # polled rule evaluation interval; minimum 5, invalid values fall back to 60diff --git a/backend/app/controllers/health_deep.go b/backend/app/controllers/health_deep.goindex a18d2398..999cc5ad 100644--- a/backend/app/controllers/health_deep.go+++ b/backend/app/controllers/health_deep.go@@ -35,6 +35,7 @@ type HealthDeepResponse struct {DroppedRows map[string]uint64 `json:"droppedRows"`DroppedRowsTotal uint64 `json:"droppedRowsTotal"`InsertFailures uint64 `json:"insertFailures"`+ IngestRejected uint64 `json:"ingestRejected"`Engine *db.TelemetryEngineStats `json:"engine,omitempty"`}@@ -49,6 +50,7 @@ func (h healthDeepController) Get(c *gin.Context) {resp.DroppedRows = droppedresp.DroppedRowsTotal = droppedTotalresp.InsertFailures = insertFailures+ resp.IngestRejected = db.GetIngestRejects()if engine, ok := db.GetTelemetryEngineStats(c.Request.Context()); ok {resp.Engine = &engine}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex ac4a5fe9..894793a3 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -35,20 +35,20 @@ type Pagination struct {func RegisterControllers(router *gin.RouterGroup) {router.OPTIONS("/report", middleware.CORSReport)- router.POST("/report", middleware.CORSReport, middleware.UseClientAuth, middleware.UseGzip, clientcontrollers.ClientController.Report)+ router.POST("/report", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, middleware.UseGzip, clientcontrollers.ClientController.Report)router.OPTIONS("/profiles/ingest", middleware.CORSReport)- router.POST("/profiles/ingest", middleware.CORSReport, middleware.UseClientAuth, middleware.UseGzip, clientcontrollers.ProfileIngestController.Ingest)+ router.POST("/profiles/ingest", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, middleware.UseGzip, clientcontrollers.ProfileIngestController.Ingest)otelGroup := router.Group("/otel")otelGroup.OPTIONS("/v1/traces", middleware.CORSReport)otelGroup.OPTIONS("/v1/metrics", middleware.CORSReport)otelGroup.OPTIONS("/v1/logs", middleware.CORSReport)otelGroup.OPTIONS("/v1development/profiles", middleware.CORSReport)- otelGroup.POST("/v1/traces", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportTraces)- otelGroup.POST("/v1/metrics", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportMetrics)- otelGroup.POST("/v1/logs", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportLogs)- otelGroup.POST("/v1development/profiles", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportProfiles)+ otelGroup.POST("/v1/traces", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, otelcontrollers.OtelController.ExportTraces)+ otelGroup.POST("/v1/metrics", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, otelcontrollers.OtelController.ExportMetrics)+ otelGroup.POST("/v1/logs", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, otelcontrollers.OtelController.ExportLogs)+ otelGroup.POST("/v1development/profiles", middleware.CORSReport, middleware.UseClientAuth, middleware.IngestAdmission, otelcontrollers.OtelController.ExportProfiles)router.GET("/projects", middleware.UseAppAuth, ProjectController.ListProjects)router.POST("/projects", middleware.UseAppAuth, middleware.RequireProjectAccess, ProjectController.CreateProject)diff --git a/backend/app/db/telemetry_stats.go b/backend/app/db/telemetry_stats.goindex a020018f..b980d6dd 100644--- a/backend/app/db/telemetry_stats.go+++ b/backend/app/db/telemetry_stats.go@@ -37,8 +37,23 @@ var (telemetryIngestMu sync.MutextelemetryDroppedRows = map[string]uint64{}telemetryInsertFailures uint64+ telemetryIngestRejects uint64)+// RecordIngestRejected counts requests turned away by the ingest admission+// gate (503). Rejects are load shedding, not data loss — the client retries.+func RecordIngestRejected() {+ telemetryIngestMu.Lock()+ telemetryIngestRejects+++ telemetryIngestMu.Unlock()+}++func GetIngestRejects() uint64 {+ telemetryIngestMu.Lock()+ defer telemetryIngestMu.Unlock()+ return telemetryIngestRejects+}+func RecordTelemetryRowDropped(table string) {telemetryIngestMu.Lock()telemetryDroppedRows[table]++diff --git a/backend/app/middleware/ingest_admission.go b/backend/app/middleware/ingest_admission.gonew file mode 100644index 00000000..a95c521d--- /dev/null+++ b/backend/app/middleware/ingest_admission.go@@ -0,0 +1,70 @@+package middleware++import (+ "net/http"+ "os"+ "runtime"+ "strconv"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/db"+)++// The telemetry ingest path decompresses and decodes every request body it+// accepts; without a bound, a burst of fat OTLP batches holds decoded copies+// of all of them in memory at once and the kernel OOM-kills the process+// (observed on 8 GB hosts under sustained log ingest — and on the DuckDB+// backend the death is followed by a WAL-replay stall on restart during+// which nothing answers). The gate caps concurrent ingest processing. The+// slot is acquired before the body is read, so a waiting request holds only+// a connection; a request that cannot get a slot within the wait window is+// rejected with 503 + Retry-After, which SDKs and OTLP collectors retry.+func newIngestAdmission(capacity int, wait time.Duration) gin.HandlerFunc {+ slots := make(chan struct{}, capacity)+ return func(c *gin.Context) {+ select {+ case slots <- struct{}{}:+ default:+ timer := time.NewTimer(wait)+ defer timer.Stop()+ select {+ case slots <- struct{}{}:+ case <-timer.C:+ db.RecordIngestRejected()+ c.Header("Retry-After", "2")+ c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "ingest saturated, retry later"})+ return+ case <-c.Request.Context().Done():+ c.Abort()+ return+ }+ }+ defer func() { <-slots }()+ c.Next()+ }+}++func ingestCapacityFromEnv() int {+ n := runtime.NumCPU() * 2+ if n < 4 {+ n = 4+ }+ if v := os.Getenv("INGEST_MAX_CONCURRENT"); v != "" {+ if parsed, err := strconv.Atoi(v); err == nil && parsed > 0 {+ n = parsed+ }+ }+ return n+}++func ingestWaitFromEnv() time.Duration {+ if v := os.Getenv("INGEST_ADMISSION_WAIT_SECONDS"); v != "" {+ if parsed, err := strconv.Atoi(v); err == nil && parsed >= 0 {+ return time.Duration(parsed) * time.Second+ }+ }+ return 5 * time.Second+}++var IngestAdmission = newIngestAdmission(ingestCapacityFromEnv(), ingestWaitFromEnv())diff --git a/backend/app/middleware/ingest_admission_test.go b/backend/app/middleware/ingest_admission_test.gonew file mode 100644index 00000000..d72eff15--- /dev/null+++ b/backend/app/middleware/ingest_admission_test.go@@ -0,0 +1,93 @@+package middleware++import (+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+)++func newAdmissionRouter(capacity int, wait time.Duration, release chan struct{}) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.POST("/ingest", newIngestAdmission(capacity, wait), func(c *gin.Context) {+ if release != nil {+ <-release+ }+ c.Status(http.StatusOK)+ })+ return r+}++func TestIngestAdmissionPassesUnderCapacity(t *testing.T) {+ r := newAdmissionRouter(2, 50*time.Millisecond, nil)+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200 under capacity, got %d", w.Code)+ }+}++func TestIngestAdmissionRejectsWhenSaturated(t *testing.T) {+ release := make(chan struct{})+ r := newAdmissionRouter(1, 50*time.Millisecond, release)++ var wg sync.WaitGroup+ wg.Add(1)+ go func() {+ defer wg.Done()+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ }()++ // Give the goroutine time to acquire the only slot; its handler then+ // blocks on the release channel, guaranteeing saturation below.+ time.Sleep(20 * time.Millisecond)++ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503 when saturated, got %d", w.Code)+ }+ if w.Header().Get("Retry-After") == "" {+ t.Fatalf("expected Retry-After header on 503")+ }++ close(release)+ wg.Wait()++ w2 := httptest.NewRecorder()+ r.ServeHTTP(w2, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ if w2.Code != http.StatusOK {+ t.Fatalf("expected 200 after release, got %d", w2.Code)+ }+}++func TestIngestAdmissionWaiterGetsSlotWhenFreed(t *testing.T) {+ release := make(chan struct{})+ r := newAdmissionRouter(1, 2*time.Second, release)++ var wg sync.WaitGroup+ wg.Add(1)+ go func() {+ defer wg.Done()+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ }()+ time.Sleep(20 * time.Millisecond)++ go func() {+ time.Sleep(50 * time.Millisecond)+ close(release)+ }()++ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/ingest", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("expected waiting request to get the freed slot, got %d", w.Code)+ }+ wg.Wait()+}diff --git a/benchmarks/loadgen/ingest.go b/benchmarks/loadgen/ingest.goindex 0bf918f2..142ac245 100644--- a/benchmarks/loadgen/ingest.go+++ b/benchmarks/loadgen/ingest.go@@ -22,6 +22,7 @@ type ingester struct {requestRate atomic.Int64 // requests/sec, scaled by 1e3 so we keep fractional resolutionattemptedItems atomic.Int64rejectedItems atomic.Int64+ okItems atomic.Int64 // items in 2xx responses minus PartialSuccess rejects — rows that actually landed// rng pool: each worker grabs one to avoid contending on the global sourcerngPool sync.Pool@@ -105,6 +106,14 @@ func (i *ingester) SnapshotAndResetItems() (attempted, rejected int64) {return}+// SnapshotAndResetOkItems returns items confirmed by 2xx responses (minus+// OTLP PartialSuccess rejects) since the last call. The read-probe fill+// tracks this instead of attempted items so admission-gate 503s and other+// HTTP failures don't count phantom rows toward a fill target.+func (i *ingester) SnapshotAndResetOkItems() int64 {+ return i.okItems.Swap(0)+}+// Start launches the worker pool sized for the current request rate. The// passed ctx is used directly for HTTP requests so in-flight requests survive// across step boundaries; the limiter loop uses a derived acceptCtx that@@ -129,7 +138,7 @@ func (i *ingester) Start(ctx context.Context) {batchSize := int(i.batchSize.Load())// HTTP uses the parent ctx (not acceptCtx) so requests in// flight when StopAccepting fires aren't canceled mid-flight.- sendOneOTLP(ctx, i.client, i.cfg, i.sender, rng, batchSize, i.stats, &i.attemptedItems, &i.rejectedItems)+ sendOneOTLP(ctx, i.client, i.cfg, i.sender, rng, batchSize, i.stats, &i.attemptedItems, &i.rejectedItems, &i.okItems)}}()}diff --git a/benchmarks/loadgen/otlp_common.go b/benchmarks/loadgen/otlp_common.goindex a2a2d9e1..ed2e9a75 100644--- a/benchmarks/loadgen/otlp_common.go+++ b/benchmarks/loadgen/otlp_common.go@@ -67,6 +67,7 @@ func sendOneOTLP(stats *latencyTracker,attemptedItems *atomic.Int64,rejectedItems *atomic.Int64,+ okItems *atomic.Int64,) {body, err := sender.BuildBody(rng, batchSize)if err != nil {@@ -104,8 +105,10 @@ func sendOneOTLP(return}- if rej := sender.ParseRejected(respBody); rej > 0 {+ rej := sender.ParseRejected(respBody)+ if rej > 0 {rejectedItems.Add(int64(rej))}+ okItems.Add(int64(batchSize) - int64(rej))stats.Record(elapsed.Seconds()*1000, nil)}diff --git a/benchmarks/loadgen/read_probe.go b/benchmarks/loadgen/read_probe.goindex 8f85670d..e34cffc5 100644--- a/benchmarks/loadgen/read_probe.go+++ b/benchmarks/loadgen/read_probe.go@@ -100,6 +100,7 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *l// Reset the ingester counters before starting so totalIngested reflects// only what this scenario sent.ing.SnapshotAndResetItems()+ ing.SnapshotAndResetOkItems()ingestStats.SnapshotAndReset()_, sutStatsBase := fetchDeepHealth(ctx, cfg, client)@@ -122,8 +123,7 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *lstep.RowsIngested = totalIngested// Drain whatever bumped between Stop and Snapshot.- extraAttempted, _ := ing.SnapshotAndResetItems()- totalIngested += extraAttempted+ totalIngested += ing.SnapshotAndResetOkItems()step.RowsIngested = totalIngestedif sutStatsBase.Reachable {@@ -139,6 +139,10 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *lif step.DigestTimedOut {fmt.Fprintf(stderrPrefix(), "read-probe: engine still digesting after %.0fs cap — probing anyway\n", step.DigestSeconds)}+ // ClickHouse's post-ingest work is merges rather than a WAL+ // checkpoint; give it the same courtesy before probing. Skips+ // instantly on backends where CH isn't reachable.+ waitForMergesIdle(ctx, cfg, client, fmt.Sprintf("fill %d -> probe", target))fmt.Fprintf(stderrPrefix(), "read-probe fill=%d rows reached in %.1fs (signal=%s) — digested in %.1fs, settling %ds\n",step.RowsIngested, step.IngestSecondsElapsed, cfg.signal, step.DigestSeconds, res.SettleSeconds)@@ -212,10 +216,12 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *lreturn res}-// pollFillProgress drains attempted-item counters from the ingester until the-// target is reached or the context cancels. Sub-second polling keeps overshoot-// small (at fill-batch=8192 × 100 req/s the loadgen sends ~800k items/sec, so-// 200ms granularity overshoots by ≤160k items — negligible at 100M fill).+// pollFillProgress drains confirmed-item counters from the ingester until the+// target is reached or the context cancels. Counting only 2xx-confirmed items+// (not attempts) keeps the fill honest when the SUT sheds load with 503s.+// Sub-second polling keeps overshoot small (at fill-batch=8192 × 100 req/s+// the loadgen sends ~800k items/sec, so 200ms granularity overshoots by+// ≤160k items — negligible at 100M fill).func pollFillProgress(ctx context.Context, ing *ingester, totalIngested *int64, target int64) {tick := time.NewTicker(200 * time.Millisecond)defer tick.Stop()@@ -224,8 +230,7 @@ func pollFillProgress(ctx context.Context, ing *ingester, totalIngested *int64,case <-ctx.Done():returncase <-tick.C:- attempted, _ := ing.SnapshotAndResetItems()- *totalIngested += attempted+ *totalIngested += ing.SnapshotAndResetOkItems()}}}