:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): rate limit by service (#57576)
Daniel Visca421997629350
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.tsindex 4fb212e9d931..6490895dce2f 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts@@ -989,7 +989,6 @@ describe('LogsIngestionConsumer', () => {expect(stats!.bytesDropped).toBe(0)expect(stats!.recordsDropped).toBe(0)expect(stats!.piiReplacements).toBe(0)- expect(stats!.samplingRecordsDropped).toBe(0)})it('should aggregate stats for multiple messages from same team', async () => {@@ -1132,7 +1131,6 @@ describe('LogsIngestionConsumer', () => {bytesDropped: 200,recordsDropped: 2,piiReplacements: 0,- samplingRecordsDropped: 3,},],])@@ -1141,7 +1139,7 @@ describe('LogsIngestionConsumer', () => {const messages = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_APP_METRICS_2)- expect(messages).toHaveLength(7)+ expect(messages).toHaveLength(6)const metricNames = messages.map((m) => parseMetricValue(m.value)?.metric_name)expect(metricNames).toContain('bytes_received')@@ -1150,7 +1148,6 @@ describe('LogsIngestionConsumer', () => {expect(metricNames).toContain('records_ingested')expect(metricNames).toContain('bytes_dropped')expect(metricNames).toContain('records_dropped')- expect(metricNames).toContain('sampling_records_dropped')})it('should skip zero-count metrics', async () => {@@ -1165,7 +1162,6 @@ describe('LogsIngestionConsumer', () => {bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,- samplingRecordsDropped: 0,},],])@@ -1203,7 +1199,6 @@ describe('LogsIngestionConsumer', () => {bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,- samplingRecordsDropped: 0,},],[@@ -1216,7 +1211,6 @@ describe('LogsIngestionConsumer', () => {bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,- samplingRecordsDropped: 0,},],])@@ -1449,7 +1443,6 @@ describe('LogsIngestionConsumer', () => {return (value.metric_name === 'bytes_dropped' ||value.metric_name === 'records_dropped' ||- value.metric_name === 'sampling_records_dropped' ||value.metric_name === 'sampling_records_dropped_by_rule')})@@ -1474,7 +1467,7 @@ describe('LogsIngestionConsumer', () => {config: { actions: { INFO: { type: 'drop' } } },},])- : { rules: [] }+ : compileRuleSet([])),}consumer = await createLogsIngestionConsumer(@@ -1485,7 +1478,7 @@ describe('LogsIngestionConsumer', () => {await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)})- it('should emit sampling_records_dropped when head sampling drops log lines', async () => {+ it('should emit sampling_records_dropped_by_rule when head sampling drops log lines', async () => {const logData = createLogMessage({ level: 'info' })const messages = await createKafkaMessages([logData], {token: team.api_token,@@ -1496,12 +1489,9 @@ describe('LogsIngestionConsumer', () => {await waitForBackgroundTasks(consumer.processKafkaBatch(messages))const appMetricsMessages = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_APP_METRICS_2)- const samplingDropped = appMetricsMessages.find((m) => {- const value = parseMetricValue(m.value)- return value.metric_name === 'sampling_records_dropped' && value.team_id === team.id- })- expect(samplingDropped).toBeDefined()- expect(parseMetricValue(samplingDropped!.value).count).toBe(1)+ expect(+ appMetricsMessages.some((m) => parseMetricValue(m.value).metric_name === 'sampling_records_dropped')+ ).toBe(false)const byRule = appMetricsMessages.find((m) => {const value = parseMetricValue(m.value)diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.tsindex 2e37f11536f4..5346993b02fc 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts@@ -21,7 +21,7 @@ import { type PiiScrubStats } from './log-pii-scrub'import { processLogMessageBuffer } from './log-record-avro'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'import type { CompiledRuleSet } from './sampling/evaluate'-import { processBufferWithSampling } from './sampling/process-buffer-with-sampling'+import { type SamplingRateContext, processBufferWithSampling } from './sampling/process-buffer-with-sampling'import { SamplingRulesCache } from './sampling/sampling-rules-cache'import { LogsRateLimiterService } from './services/logs-rate-limiter.service'import { LogsIngestionMessage } from './types'@@ -48,8 +48,6 @@ export type UsageStats = {bytesDropped: numberrecordsDropped: numberpiiReplacements: number- /** Log lines dropped by head sampling / drop rules (not quota or rate limit). */- samplingRecordsDropped: number}const DEFAULT_USAGE_STATS: UsageStats = {@@ -60,7 +58,6 @@ const DEFAULT_USAGE_STATS: UsageStats = {bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,- samplingRecordsDropped: 0,}export type UsageStatsByTeam = Map<number, UsageStats>@@ -127,6 +124,7 @@ export class LogsIngestionConsumer {private appMetricsAggregator: AppMetricsAggregatorprivate redis: RedisV2private rateLimiter: LogsRateLimiterService+ private readonly logsSamplingRateLimitTtlSeconds: numberprivate readonly samplingEnabledTeamsRaw: stringprivate readonly samplingKillswitch: boolean@@ -162,6 +160,7 @@ export class LogsIngestionConsumer {poolMaxSize: config.REDIS_POOL_MAX_SIZE,})this.rateLimiter = new LogsRateLimiterService(config, this.redis)+ this.logsSamplingRateLimitTtlSeconds = config.LOGS_LIMITER_TTL_SECONDSthis.samplingEnabledTeamsRaw = overrides.LOGS_SAMPLING_ENABLED_TEAMS ?? config.LOGS_SAMPLING_ENABLED_TEAMSthis.samplingKillswitch = overrides.LOGS_SAMPLING_KILLSWITCH ?? config.LOGS_SAMPLING_KILLSWITCH}@@ -227,7 +226,14 @@ export class LogsIngestionConsumer {})if (useSamplingPipeline && ruleSet) {- const sampled = await processBufferWithSampling(message.message.value!, logsSettings, ruleSet)+ const rateCtx: SamplingRateContext | null = ruleSet.hasRateLimitRules+ ? {+ teamId: message.teamId,+ redis: this.redis,+ ttlSeconds: this.logsSamplingRateLimitTtlSeconds,+ }+ : null+ const sampled = await processBufferWithSampling(message.message.value!, logsSettings, ruleSet, rateCtx)if (sampled.recordsDropped > 0) {logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)}@@ -359,15 +365,6 @@ export class LogsIngestionConsumer {usage.set(teamId, row)}- private addSamplingRecordsDroppedIntoUsage(usage: UsageStatsByTeam, teamId: number, count: number): void {- if (count === 0) {- return- }- const row = usage.get(teamId) || { ...DEFAULT_USAGE_STATS }- row.samplingRecordsDropped += count- usage.set(teamId, row)- }-private async filterQuotaLimitedMessages(messages: LogsIngestionMessage[]): Promise<{ quotaAllowedMessages: LogsIngestionMessage[]; quotaDroppedMessages: LogsIngestionMessage[] }> {@@ -461,13 +458,11 @@ export class LogsIngestionConsumer {1)this.addPiiStatsIntoUsage(usageStats, message.teamId, resolved.pii)- this.addSamplingRecordsDroppedIntoUsage(usageStats, message.teamId, resolved.recordsDropped)this.queueSamplingRecordsDroppedByRule(message.teamId, resolved.recordsDroppedByRuleId)return Promise.resolve()}- const { processedValue, pii, recordsDropped, recordsDroppedByRuleId } = resolved+ const { processedValue, pii, recordsDroppedByRuleId } = resolvedthis.addPiiStatsIntoUsage(usageStats, message.teamId, pii)- this.addSamplingRecordsDroppedIntoUsage(usageStats, message.teamId, recordsDropped)this.queueSamplingRecordsDroppedByRule(message.teamId, recordsDroppedByRuleId)// Await so a rejection here lands in the catch and routes to the DLQ.@@ -539,7 +534,6 @@ export class LogsIngestionConsumer {this.queueUsageMetric(teamId, 'bytes_dropped', stats.bytesDropped)this.queueUsageMetric(teamId, 'records_dropped', stats.recordsDropped)this.queueUsageMetric(teamId, 'pii_replacements', stats.piiReplacements)- this.queueUsageMetric(teamId, 'sampling_records_dropped', stats.samplingRecordsDropped)}// Best-effort: don't let metric failures block ingestion@@ -565,7 +559,10 @@ export class LogsIngestionConsumer {})}- /** Per-rule head sampling drops; `instance_id` is the LogsExclusionRule UUID (app_metrics2 dimension). */+ /**+ * Per-rule head sampling drops in app_metrics2 (`sampling_records_dropped_by_rule`).+ * Team-level sampling volume in CH is `sum(count)` over those rows (no separate aggregate metric).+ */private queueSamplingRecordsDroppedByRule(teamId: number, byRule: Map<string, number>): void {for (const [ruleId, count] of byRule) {if (count <= 0) {diff --git a/nodejs/src/logs-ingestion/sampling/compile-rules.ts b/nodejs/src/logs-ingestion/sampling/compile-rules.tsindex 6cc30db19b25..73c0510e48b2 100644--- a/nodejs/src/logs-ingestion/sampling/compile-rules.ts+++ b/nodejs/src/logs-ingestion/sampling/compile-rules.ts@@ -45,6 +45,27 @@ function parseSeverityActions(raw: unknown): [SeverityAction, SeverityAction, Sereturn out}+const MAX_LOGS_PER_SECOND = 1_000_000+const MAX_BURST_LOGS = 60_000_000++function parseRateLimitFromConfig(+ config: Record<string, unknown>+): { refillPerSecond: number; poolMax: number } | null {+ const lps = config.logs_per_second+ if (typeof lps !== 'number' || !Number.isFinite(lps) || lps < 1 || lps > MAX_LOGS_PER_SECOND) {+ return null+ }+ const refill = Math.floor(lps)+ const burstRaw = config.burst_logs+ let poolMax: number+ if (typeof burstRaw === 'number' && Number.isFinite(burstRaw) && burstRaw >= refill) {+ poolMax = Math.min(Math.floor(burstRaw), MAX_BURST_LOGS)+ } else {+ poolMax = Math.min(refill * 3, MAX_BURST_LOGS)+ }+ return { refillPerSecond: refill, poolMax }+}+function parseAlwaysKeep(config: Record<string, unknown>): CompiledSamplingRule['alwaysKeep'] {const ak = config.always_keep as Record<string, unknown> | undefinedif (!ak || typeof ak !== 'object') {@@ -68,6 +89,7 @@ function parseAlwaysKeep(config: Record<string, unknown>): CompiledSamplingRule[export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {const rules: CompiledSamplingRule[] = []+ let hasRateLimitRules = falsefor (const row of rows) {let pathRegex: RegExp | null = nullif (row.scope_path_pattern) {@@ -99,16 +121,26 @@ export function compileRuleSet(rows: SamplingRuleRow[]): CompiledRuleSet {}}const rt = row.rule_type as CompiledSamplingRule['ruleType']+ const ruleType: CompiledSamplingRule['ruleType'] =+ rt === 'path_drop' || rt === 'rate_limit' || rt === 'severity_sampling' ? rt : 'path_drop'+ let rateLimit: CompiledSamplingRule['rateLimit'] = null+ if (ruleType === 'rate_limit') {+ rateLimit = parseRateLimitFromConfig(row.config ?? {})+ if (rateLimit) {+ hasRateLimitRules = true+ }+ }rules.push({id: row.id,- ruleType: rt === 'path_drop' || rt === 'rate_limit' || rt === 'severity_sampling' ? rt : 'path_drop',+ ruleType,scopeService: row.scope_service,pathRegex,pathDropPatterns,pathDropMatchAttributeKey,severityActions: parseSeverityActions(row.config),alwaysKeep: parseAlwaysKeep(row.config),+ rateLimit,})}- return { rules }+ return { rules, hasRateLimitRules }}diff --git a/nodejs/src/logs-ingestion/sampling/evaluate.test.ts b/nodejs/src/logs-ingestion/sampling/evaluate.test.tsindex b4dd649c9321..d6a4010ca80f 100644--- a/nodejs/src/logs-ingestion/sampling/evaluate.test.ts+++ b/nodejs/src/logs-ingestion/sampling/evaluate.test.ts@@ -4,6 +4,7 @@ import {SAMPLING_DECISION_DROP,SAMPLING_DECISION_SAMPLE_DROPPED,SAMPLING_DECISION_SAMPLE_KEPT,+ classifySamplingRecord,evaluateLogRecord,severityOrdinalFromRecord,} from './evaluate'@@ -158,4 +159,78 @@ describe('evaluateLogRecord', () => {const elapsed = Date.now() - t0expect(elapsed).toBeLessThan(10_000)})++ it('compileRuleSet marks hasRateLimitRules for valid rate_limit config', () => {+ const rs = compileRuleSet([+ {+ id: 'rl',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 100, burst_logs: 300 },+ },+ ])+ expect(rs.hasRateLimitRules).toBe(true)+ expect(rs.rules[0]?.rateLimit).toEqual({ refillPerSecond: 100, poolMax: 300 })+ })++ it('classifySamplingRecord defers to rate_limit when first matching rule', () => {+ const rules = compileRuleSet([+ {+ id: 'rl',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 10 },+ },+ ])+ const rec = baseRecord()+ rec.service_name = 'api'+ expect(classifySamplingRecord(rules, rec)).toEqual({ kind: 'rate_limit', ruleId: 'rl' })+ })++ it('classifySamplingRecord skips rate_limit when service scope does not match', () => {+ const rules = compileRuleSet([+ {+ id: 'rl',+ rule_type: 'rate_limit',+ scope_service: 'other',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 10 },+ },+ ])+ const rec = baseRecord()+ rec.service_name = 'api'+ expect(classifySamplingRecord(rules, rec).kind).toBe('resolved')+ })++ it('path_drop match runs before rate_limit in rule order', () => {+ const rules = compileRuleSet([+ {+ id: 'pd',+ rule_type: 'path_drop',+ scope_service: null,+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { patterns: ['/healthz'] },+ },+ {+ id: 'rl',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 10 },+ },+ ])+ const rec = baseRecord()+ expect(classifySamplingRecord(rules, rec)).toEqual({+ kind: 'resolved',+ decision: SAMPLING_DECISION_DROP,+ ruleId: 'pd',+ })+ })})diff --git a/nodejs/src/logs-ingestion/sampling/evaluate.ts b/nodejs/src/logs-ingestion/sampling/evaluate.tsindex e3923d2784c9..523eeb4888c1 100644--- a/nodejs/src/logs-ingestion/sampling/evaluate.ts+++ b/nodejs/src/logs-ingestion/sampling/evaluate.ts@@ -29,10 +29,14 @@ export type CompiledSamplingRule = {latencyMsGt: number | nullattributePredicates: { key: string; op: string; value?: string }[]} | null+ /** Set for rate_limit rules with valid config; ingestion uses Redis token bucket (logs/sec). */+ rateLimit: { refillPerSecond: number; poolMax: number } | null}export type CompiledRuleSet = {rules: CompiledSamplingRule[]+ /** True when any compiled rule applies per-line Redis rate limiting. */+ hasRateLimitRules: boolean}const SEV_ORD_DEBUG = 0@@ -153,6 +157,66 @@ export type EvaluateResult = {ruleId: string | null}+export type SamplingClassifyResult =+ | { kind: 'resolved'; decision: SamplingDecision; ruleId: string | null }+ | { kind: 'rate_limit'; ruleId: string }++export type RateLimitPendingByRule = Map<string, number[]>++/**+ * Stateless rule walk for ingestion. When the first applicable rule is `rate_limit` with a compiled+ * bucket, returns `rate_limit` so the caller can batch Redis checks. Otherwise matches `evaluateLogRecord`.+ */+export function classifySamplingRecord(teamRuleSet: CompiledRuleSet | null, record: LogRecord): SamplingClassifyResult {+ if (!teamRuleSet || teamRuleSet.rules.length === 0) {+ return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: null }+ }+ const ord = severityOrdinalFromRecord(record)+ for (const rule of teamRuleSet.rules) {+ if (!matchesScope(rule, record)) {+ continue+ }+ if (alwaysKeepMatches(rule, record)) {+ return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: rule.id }+ }+ if (rule.ruleType === 'path_drop') {+ if (!rule.pathDropPatterns || rule.pathDropPatterns.length === 0) {+ continue+ }+ const p = rule.pathDropMatchAttributeKey+ ? (getAttribute(record, rule.pathDropMatchAttributeKey) ?? '')+ : pathForMatching(record)+ for (const rx of rule.pathDropPatterns) {+ if (rx.test(p)) {+ return { kind: 'resolved', decision: SAMPLING_DECISION_DROP, ruleId: rule.id }+ }+ }+ continue+ }+ if (rule.ruleType === 'severity_sampling') {+ const action = rule.severityActions[ord]+ if (action.type === 'keep') {+ return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: rule.id }+ }+ if (action.type === 'drop') {+ return { kind: 'resolved', decision: SAMPLING_DECISION_DROP, ruleId: rule.id }+ }+ const u = hash01FromTraceId(record.trace_id)+ if (u < action.rate) {+ return { kind: 'resolved', decision: SAMPLING_DECISION_SAMPLE_KEPT, ruleId: rule.id }+ }+ return { kind: 'resolved', decision: SAMPLING_DECISION_SAMPLE_DROPPED, ruleId: rule.id }+ }+ if (rule.ruleType === 'rate_limit') {+ if (rule.rateLimit) {+ return { kind: 'rate_limit', ruleId: rule.id }+ }+ continue+ }+ }+ return { kind: 'resolved', decision: SAMPLING_DECISION_KEEP, ruleId: null }+}+export function evaluateLogRecord(teamRuleSet: CompiledRuleSet | null, record: LogRecord): EvaluateResult {if (!teamRuleSet || teamRuleSet.rules.length === 0) {return { decision: SAMPLING_DECISION_KEEP, ruleId: null }@@ -194,6 +258,7 @@ export function evaluateLogRecord(teamRuleSet: CompiledRuleSet | null, record: Lreturn { decision: SAMPLING_DECISION_SAMPLE_DROPPED, ruleId: rule.id }}if (rule.ruleType === 'rate_limit') {+ // Stateful in ingestion; stateless evaluation does not drop here.continue}}diff --git a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.ts b/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.tsnew file mode 100644index 000000000000..30f2622d4b5f--- /dev/null+++ b/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.test.ts@@ -0,0 +1,118 @@+import avro from 'avsc'++import type { RedisClientPipeline, RedisV2 } from '~/common/redis/redis-v2'+import type { LogsSettings } from '~/types'++import { type LogRecord, decodeLogRecords, encodeLogRecords } from '../log-record-avro'+import { compileRuleSet } from './compile-rules'+import { type SamplingRateContext, processBufferWithSampling } from './process-buffer-with-sampling'++const LOG_RECORD_AVRO = avro.Type.forSchema({+ type: 'record',+ name: 'LogRecord',+ fields: [+ { name: 'uuid', type: ['null', 'string'] },+ { name: 'trace_id', type: ['null', 'bytes'] },+ { name: 'span_id', type: ['null', 'bytes'] },+ { name: 'trace_flags', type: ['null', 'int'] },+ { name: 'timestamp', type: ['null', 'long'] },+ { name: 'observed_timestamp', type: ['null', 'long'] },+ { name: 'body', type: ['null', 'string'] },+ { name: 'severity_text', type: ['null', 'string'] },+ { name: 'severity_number', type: ['null', 'int'] },+ { name: 'service_name', type: ['null', 'string'] },+ { name: 'resource_attributes', type: ['null', { type: 'map', values: 'string' }] },+ { name: 'instrumentation_scope', type: ['null', 'string'] },+ { name: 'event_name', type: ['null', 'string'] },+ { name: 'attributes', type: ['null', { type: 'map', values: 'string' }] },+ ],+})++const logsSettings: LogsSettings = { json_parse_logs: false, pii_scrub_logs: false }++function baseLog(uuid: string, serviceName: string): LogRecord {+ return {+ uuid,+ trace_id: null,+ span_id: null,+ trace_flags: null,+ timestamp: 1_700_000_000_000_000,+ observed_timestamp: 1_700_000_000_000_000,+ body: 'x',+ severity_text: 'info',+ severity_number: 9,+ service_name: serviceName,+ resource_attributes: null,+ instrumentation_scope: null,+ event_name: null,+ attributes: null,+ }+}++describe('processBufferWithSampling', () => {+ it('batches rate_limit lines and drops when tokensBefore is below pending count', async () => {+ const ruleSet = compileRuleSet([+ {+ id: 'rl-1',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 100, burst_logs: 1000 },+ },+ ])+ const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [+ baseLog('a', 'api'),+ baseLog('b', 'api'),+ baseLog('c', 'api'),+ ])++ const mockRedis: RedisV2 = {+ useClient: jest.fn(() => Promise.resolve(null)),+ usePipeline: jest.fn((_opts, cb) => {+ const pipeline = { checkRateLimitV2: jest.fn() } as unknown as RedisClientPipeline+ cb(pipeline)+ const pipelineResult: [Error | null, any][] = [[null, [2, 0] as const]]+ return Promise.resolve(pipelineResult)+ }),+ }++ const rateCtx: SamplingRateContext = { teamId: 99, redis: mockRedis, ttlSeconds: 60 }+ const result = await processBufferWithSampling(buffer, logsSettings, ruleSet, rateCtx)++ expect(result.recordsDropped).toBe(1)+ expect(result.recordsDroppedByRuleId.get('rl-1')).toBe(1)+ expect(result.allDropped).toBe(false)++ const [, , kept] = await decodeLogRecords(result.value)+ expect(kept).toHaveLength(2)+ })++ it('fail-open keeps all rate_limit lines when Redis pipeline returns null', async () => {+ const ruleSet = compileRuleSet([+ {+ id: 'rl-1',+ rule_type: 'rate_limit',+ scope_service: 'api',+ scope_path_pattern: null,+ scope_attribute_filters: [],+ config: { logs_per_second: 10 },+ },+ ])+ const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [baseLog('a', 'api'), baseLog('b', 'api')])++ const mockRedis: RedisV2 = {+ useClient: jest.fn(() => Promise.resolve(null)),+ usePipeline: jest.fn(() => Promise.resolve(null)),+ }++ const rateCtx: SamplingRateContext = { teamId: 1, redis: mockRedis, ttlSeconds: 60 }+ const result = await processBufferWithSampling(buffer, logsSettings, ruleSet, rateCtx)++ expect(result.recordsDropped).toBe(0)+ expect(result.recordsDroppedByRuleId.size).toBe(0)++ const [, , kept] = await decodeLogRecords(result.value)+ expect(kept).toHaveLength(2)+ })+})diff --git a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.ts b/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.tsindex 0d409249a223..730e33cb6bf9 100644--- a/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.ts+++ b/nodejs/src/logs-ingestion/sampling/process-buffer-with-sampling.ts@@ -1,5 +1,6 @@import { trace } from '@opentelemetry/api'+import { type RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'import { instrumented } from '~/common/tracing/tracing-utils'import type { LogsSettings } from '~/types'@@ -10,11 +11,25 @@ import {encodeLogRecords,transformDecodedLogRecordsInPlace,} from '../log-record-avro'-import type { CompiledRuleSet } from './evaluate'-import { SAMPLING_DECISION_DROP, SAMPLING_DECISION_SAMPLE_DROPPED, evaluateLogRecord } from './evaluate'+import type { CompiledRuleSet, RateLimitPendingByRule, SamplingClassifyResult } from './evaluate'+import {+ SAMPLING_DECISION_DROP,+ SAMPLING_DECISION_SAMPLE_DROPPED,+ classifySamplingRecord,+ evaluateLogRecord,+} from './evaluate'const samplingProcessInstrumentOpts = { measureTime: false, sendException: false } as const+const SAMPLING_RATE_LIMIT_REDIS_PREFIX =+ process.env.NODE_ENV === 'test' ? '@posthog-test/logs-sampling-rate' : '@posthog/logs-sampling-rate'++export type SamplingRateContext = {+ teamId: number+ redis: RedisV2+ ttlSeconds: number+}+export type ProcessBufferWithSamplingResult = {value: Bufferpii: PiiScrubStats@@ -25,10 +40,86 @@ export type ProcessBufferWithSamplingResult = {allDropped: boolean}+async function applySamplingRateLimits(+ teamId: number,+ redis: RedisV2,+ ttlSeconds: number,+ ruleSet: CompiledRuleSet,+ pendingByRule: RateLimitPendingByRule,+ nowSeconds: number+): Promise<Map<number, boolean>> {+ /** recordIndex -> keep (true) or drop (false) when classification was rate_limit */+ const keepByIndex = new Map<number, boolean>()++ if (pendingByRule.size === 0) {+ return keepByIndex+ }++ const ruleById = new Map(ruleSet.rules.map((r) => [r.id, r]))+ const pipelineArgs: { ruleId: string; cost: number; poolMax: number; fillRate: number; key: string }[] = []++ for (const [ruleId, indices] of pendingByRule) {+ const rule = ruleById.get(ruleId)+ const rl = rule?.rateLimit+ if (!rl || indices.length === 0) {+ continue+ }+ pipelineArgs.push({+ ruleId,+ cost: indices.length,+ poolMax: rl.poolMax,+ fillRate: rl.refillPerSecond,+ key: `${SAMPLING_RATE_LIMIT_REDIS_PREFIX}/${teamId}/${ruleId}`,+ })+ }++ if (pipelineArgs.length === 0) {+ for (const [, indices] of pendingByRule) {+ for (const idx of indices) {+ keepByIndex.set(idx, true)+ }+ }+ return keepByIndex+ }++ const res = await redis.usePipeline({ name: 'logs-sampling-rate-limit', failOpen: true }, (pipeline) => {+ for (const a of pipelineArgs) {+ pipeline.checkRateLimitV2(a.key, nowSeconds, a.cost, a.poolMax, a.fillRate, ttlSeconds)+ }+ })++ if (!res) {+ for (const [, indices] of pendingByRule) {+ for (const idx of indices) {+ keepByIndex.set(idx, true)+ }+ }+ return keepByIndex+ }++ for (let pi = 0; pi < pipelineArgs.length; pi++) {+ const arg = pipelineArgs[pi]!+ const { ruleId, poolMax: argPoolMax } = arg+ const rule = ruleById.get(ruleId)+ const poolMax = rule?.rateLimit?.poolMax ?? argPoolMax+ const [tokenRes] = getRedisPipelineResults(res, pi, 1)+ const tokensBefore = Number(tokenRes[1]?.[0] ?? poolMax)+ const indices = pendingByRule.get(ruleId) ?? []+ const budget = Math.max(0, Math.floor(tokensBefore))+ const toAdmit = Math.min(indices.length, budget)+ for (let j = 0; j < indices.length; j++) {+ keepByIndex.set(indices[j]!, j < toAdmit)+ }+ }++ return keepByIndex+}+async function processBufferWithSamplingImpl(buffer: Buffer,settings: LogsSettings,- ruleSet: CompiledRuleSet+ ruleSet: CompiledRuleSet,+ rateCtx?: SamplingRateContext | null): Promise<ProcessBufferWithSamplingResult> {const [logRecordType, compressionCodec, records] = await decodeLogRecords(buffer)if (!logRecordType) {@@ -39,16 +130,63 @@ async function processBufferWithSamplingImpl(let recordsDropped = 0const recordsDroppedByRuleId = new Map<string, number>()- for (const record of records) {- const { decision, ruleId } = evaluateLogRecord(ruleSet, record)- if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {- recordsDropped++- if (ruleId != null) {- recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)+ const useRate = Boolean(ruleSet.hasRateLimitRules && rateCtx)++ if (useRate && rateCtx) {+ const classifications: SamplingClassifyResult[] = records.map((r) => classifySamplingRecord(ruleSet, r))+ const pendingByRule: RateLimitPendingByRule = new Map()+ for (let i = 0; i < records.length; i++) {+ const c = classifications[i]!+ if (c.kind === 'rate_limit') {+ const list = pendingByRule.get(c.ruleId) ?? []+ list.push(i)+ pendingByRule.set(c.ruleId, list)}- continue}- kept.push(record)+ const nowSeconds = Math.floor(Date.now() / 1000)+ const rateKeep = await applySamplingRateLimits(+ rateCtx.teamId,+ rateCtx.redis,+ rateCtx.ttlSeconds,+ ruleSet,+ pendingByRule,+ nowSeconds+ )++ for (let i = 0; i < records.length; i++) {+ const record = records[i]!+ const c = classifications[i]!+ if (c.kind === 'rate_limit') {+ const allow = rateKeep.get(i) !== false+ if (!allow) {+ recordsDropped+++ recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)+ continue+ }+ kept.push(record)+ continue+ }+ if (c.decision === SAMPLING_DECISION_DROP || c.decision === SAMPLING_DECISION_SAMPLE_DROPPED) {+ recordsDropped+++ if (c.ruleId != null) {+ recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)+ }+ continue+ }+ kept.push(record)+ }+ } else {+ for (const record of records) {+ const { decision, ruleId } = evaluateLogRecord(ruleSet, record)+ if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {+ recordsDropped+++ if (ruleId != null) {+ recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)+ }+ continue+ }+ kept.push(record)+ }}trace.getActiveSpan()?.setAttributes({diff --git a/products/logs/backend/sampling_api.py b/products/logs/backend/sampling_api.pyindex 18eadf5141b8..f1c8fc6d3d20 100644--- a/products/logs/backend/sampling_api.py+++ b/products/logs/backend/sampling_api.py@@ -37,7 +37,7 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):)rule_type = serializers.ChoiceField(choices=LogsExclusionRule.RuleType.choices,- help_text="Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).",+ help_text="Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).",)scope_service = serializers.CharField(required=False,@@ -65,7 +65,9 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):"`match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same ""virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is ""tested only against that string attribute on the log record. For severity_sampling: object with "- "`actions` per severity level and optional `always_keep`. rate_limit is reserved."+ "`actions` per severity level and optional `always_keep`. For rate_limit: object with required "+ "`logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); "+ "rate_limit rules require non-null `scope_service` matching `service.name` on each log line."))version = serializers.IntegerField(@@ -114,6 +116,33 @@ class LogsSamplingRuleSerializer(serializers.ModelSerializer):mak = config.get("match_attribute_key")if mak is not None and mak != "" and not isinstance(mak, str):raise ValidationError({"config": {"match_attribute_key": "Must be a string when provided."}})+ if rule_type == LogsExclusionRule.RuleType.RATE_LIMIT:+ if not isinstance(config, dict):+ raise ValidationError({"config": "rate_limit rules require config to be a JSON object."})+ scope_service = attrs.get("scope_service")+ if scope_service is None and self.instance is not None:+ scope_service = self.instance.scope_service+ if not scope_service or not str(scope_service).strip():+ raise ValidationError(+ {"scope_service": "rate_limit rules require a non-empty service name (service.name on logs)."}+ )+ lps = config.get("logs_per_second")+ if isinstance(lps, bool) or not isinstance(lps, int):+ raise ValidationError(+ {"config": {"logs_per_second": "Must be an integer (logs per second sustained)."}}+ )+ if lps < 1 or lps > 1_000_000:+ raise ValidationError({"config": {"logs_per_second": "Must be between 1 and 1000000 inclusive."}})+ burst = config.get("burst_logs", None)+ if burst is not None:+ if isinstance(burst, bool) or not isinstance(burst, int):+ raise ValidationError({"config": {"burst_logs": "Must be an integer when provided."}})+ if burst < lps:+ raise ValidationError(+ {"config": {"burst_logs": "Must be greater than or equal to logs_per_second."}}+ )+ if burst > 60_000_000:+ raise ValidationError({"config": {"burst_logs": "Must be at most 60000000."}})return attrsdef validate_scope_attribute_filters(self, value: Any) -> Any:diff --git a/products/logs/backend/test/test_sampling_rules_api.py b/products/logs/backend/test/test_sampling_rules_api.pyindex 5ceaa98e83fe..5fee2c1e0902 100644--- a/products/logs/backend/test/test_sampling_rules_api.py+++ b/products/logs/backend/test/test_sampling_rules_api.py@@ -64,3 +64,35 @@ class TestLogsSamplingRulesAPI(APIBaseTest):assert ordered[0]["priority"] == 0assert ordered[1]["id"] == a["id"]assert ordered[1]["priority"] == 1++ def test_create_rate_limit_requires_scope_service(self):+ response = self.client.post(+ self.base_url,+ self._payload(+ name="Cap api",+ rule_type="rate_limit",+ scope_service=None,+ config={"logs_per_second": 100},+ ),+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "scope_service"++ def test_create_rate_limit_success(self):+ response = self.client.post(+ self.base_url,+ self._payload(+ name="Cap api",+ rule_type="rate_limit",+ scope_service="payment-api",+ config={"logs_per_second": 5000, "burst_logs": 15000},+ ),+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["rule_type"] == "rate_limit"+ assert body["scope_service"] == "payment-api"+ assert body["config"]["logs_per_second"] == 5000+ assert body["config"]["burst_logs"] == 15000diff --git a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsxindex d55c462f497f..c3db1c52dd04 100644--- a/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx+++ b/products/logs/frontend/components/LogsSampling/LogsSamplingForm.tsx@@ -4,6 +4,7 @@ import { LemonBanner, LemonInput, LemonSelect, LemonSwitch, LemonTag, LemonTextAimport { LemonField } from 'lib/lemon-ui/LemonField'+import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'import { RuleTypeEnumApi } from 'products/logs/frontend/generated/api.schemas'import { LogsSamplingFormType, PathDropMatchTarget, SeverityActionChoice } from './logsSamplingFormLogic'@@ -19,6 +20,10 @@ const RULE_TYPE_OPTIONS_CREATE: { value: RuleTypeEnumApi; label: string }[] = [value: RuleTypeEnumApi.SeveritySampling,label: 'Drop by severity',},+ {+ value: RuleTypeEnumApi.RateLimit,+ label: 'Rate limit by service (logs/sec)',+ },]const PATH_DROP_MATCH_TARGET_OPTIONS: { value: PathDropMatchTarget; label: string }[] = [@@ -49,12 +54,21 @@ function SeverityRow({ label, actionKey }: { label: string; actionKey: keyof Log}export function LogsSamplingForm(): JSX.Element {- const { samplingForm, samplingFormErrors, simulation, simulationLoading, canSimulate, isNewRule } =- useValues(logsSamplingFormLogic)+ const {+ samplingForm,+ samplingFormErrors,+ simulation,+ simulationLoading,+ canSimulate,+ isNewRule,+ serviceTraffic,+ serviceTrafficLoading,+ } = useValues(logsSamplingFormLogic)const { setSamplingFormValue } = useActions(logsSamplingFormLogic)const isPathDrop = samplingForm.rule_type === RuleTypeEnumApi.PathDropconst isSeverity = samplingForm.rule_type === RuleTypeEnumApi.SeveritySampling+ const isRateLimit = samplingForm.rule_type === RuleTypeEnumApi.RateLimitreturn (<div className="flex flex-col gap-4 max-w-3xl">@@ -72,7 +86,7 @@ export function LogsSamplingForm(): JSX.Element {: 'Impact estimate will appear after you save or change the rule.'}</LemonBanner>)}- <LemonField.Pure label="Name">+ <LemonField.Pure label="Name" error={samplingFormErrors.name}><LemonInputvalue={samplingForm.name}onChange={(v) => setSamplingFormValue('name', v)}@@ -89,7 +103,9 @@ export function LogsSamplingForm(): JSX.Element {help={<>“Drop by severity” is for whole severity levels (debug, info, warn, error). “Drop when- matched” is for regex on a path string or one attribute you pick.+ matched” is for regex on a path string or one attribute you pick. “Rate limit by service”+ caps how many log lines per second from one service are stored (extras are dropped at+ ingestion).</>}>@@ -104,26 +120,70 @@ export function LogsSamplingForm(): JSX.Element {<LemonTag>{ruleTypeLabel(samplingForm.rule_type)}</LemonTag></LemonField.Pure>)}- <LemonField.Pure- label="Scope: service name (optional)"- info="If set, the rule only runs for logs from this service.name. Leave empty to apply to all services."- >- <LemonInput- value={samplingForm.scope_service}- onChange={(v) => setSamplingFormValue('scope_service', v)}- placeholder="Empty = all services"- />- </LemonField.Pure>- <LemonField.Pure- label="Limit rule to matching path (optional)"- info="If set, this rule only runs for log lines where this regex matches the automatic path string (first non-empty among url.path, http.path, http.route, path). Separate from “what your drop patterns match” below. Applies to severity rules too."- >- <LemonInput- value={samplingForm.scope_path_pattern}- onChange={(v) => setSamplingFormValue('scope_path_pattern', v)}- placeholder="e.g. ^/api/internal/"- />- </LemonField.Pure>+ {isRateLimit ? (+ <>+ <LemonBanner type="info">+ <div className="text-sm">+ <strong>Which service?</strong> This must match the log's OpenTelemetry{' '}+ <code className="text-xs font-mono bg-bg-mid rounded px-1 py-0.5">service.name</code>{' '}+ exactly (same string as the Service column or log details—no wildcards, case-sensitive).+ Example:{' '}+ <code className="text-xs font-mono bg-bg-mid rounded px-1 py-0.5">payment-api</code>.+ </div>+ </LemonBanner>+ <LemonField.Pure+ label="Service"+ help="Pick from names seen in the last 24h, or type the full name in the field below if it does not appear in the list."+ error={samplingFormErrors.scope_service}+ >+ <div className="flex flex-col gap-2">+ <ServiceFilter+ selectionMode="single"+ emptyButtonLabel="Pick from last 24h…"+ value={samplingForm.scope_service ? [samplingForm.scope_service] : []}+ onChange={(names) => setSamplingFormValue('scope_service', names[0] ?? '')}+ dateRange={{ date_from: '-24h', date_to: null }}+ />+ <LemonInput+ value={samplingForm.scope_service}+ onChange={(v) => setSamplingFormValue('scope_service', v)}+ placeholder="Type exact service.name (required)"+ />+ {serviceTrafficLoading ? (+ <span className="text-muted text-sm">Loading recent volume…</span>+ ) : serviceTraffic && samplingForm.scope_service.trim() ? (+ <span className="text-muted text-sm">+ ~{serviceTraffic.avg_logs_per_sec.toFixed(2)} logs/sec average over the last 24h (+ {serviceTraffic.log_count.toLocaleString()} lines).+ </span>+ ) : null}+ </div>+ </LemonField.Pure>+ </>+ ) : (+ <LemonField.Pure+ label="Scope: service name (optional)"+ info="If set, the rule only runs for logs from this service.name. Leave empty to apply to all services."+ >+ <LemonInput+ value={samplingForm.scope_service}+ onChange={(v) => setSamplingFormValue('scope_service', v)}+ placeholder="Empty = all services"+ />+ </LemonField.Pure>+ )}+ {!isRateLimit ? (+ <LemonField.Pure+ label="Limit rule to matching path (optional)"+ info="If set, this rule only runs for log lines where this regex matches the automatic path string (first non-empty among url.path, http.path, http.route, path). Separate from “what your drop patterns match” below. Applies to severity rules too."+ >+ <LemonInput+ value={samplingForm.scope_path_pattern}+ onChange={(v) => setSamplingFormValue('scope_path_pattern', v)}+ placeholder="e.g. ^/api/internal/"+ />+ </LemonField.Pure>+ ) : null}{isPathDrop ? (<><LemonField.Pure@@ -214,6 +274,42 @@ export function LogsSamplingForm(): JSX.Element {</LemonField.Pure></>) : null}+ {isRateLimit ? (+ <>+ <LemonBanner type="info">+ <div className="text-sm">+ <strong>How limits work:</strong> lines above your sustained cap are dropped at ingestion.+ Optional <strong>burst</strong> is how many lines can be stored in a short spike before the+ limiter pulls you back toward the sustained rate. Example: sustained{' '}+ <code className="text-xs font-mono bg-bg-mid rounded px-1 py-0.5">100</code>, burst{' '}+ <code className="text-xs font-mono bg-bg-mid rounded px-1 py-0.5">300</code> — you can admit+ up to 300 lines quickly, then stored volume trends toward ~100/sec for this service.+ </div>+ </LemonBanner>+ <LemonField.Pure+ label="Sustained limit (lines per second)"+ help="Whole number from 1 to 1,000,000. Average stored lines/sec for this service while this rule is the first match."+ error={samplingFormErrors.rate_limit_logs_per_second}+ >+ <LemonInput+ value={samplingForm.rate_limit_logs_per_second}+ onChange={(v) => setSamplingFormValue('rate_limit_logs_per_second', v)}+ placeholder="e.g. 5000"+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Burst capacity (optional)"+ help="Whole number at least equal to sustained, up to 60,000,000, or leave empty for 3× sustained. Larger burst allows a bigger one-off spike before extra lines drop."+ error={samplingFormErrors.rate_limit_burst_logs}+ >+ <LemonInput+ value={samplingForm.rate_limit_burst_logs}+ onChange={(v) => setSamplingFormValue('rate_limit_burst_logs', v)}+ placeholder="Empty = 3× sustained"+ />+ </LemonField.Pure>+ </>+ ) : null}{isSeverity ? (<><LemonBanner type="info">diff --git a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.tsindex 7f81da57f8fe..282a9cf2639e 100644--- a/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts+++ b/products/logs/frontend/components/LogsSampling/logsSamplingFormLogic.ts@@ -11,6 +11,7 @@ import {logsSamplingRulesCreate,logsSamplingRulesPartialUpdate,logsSamplingRulesSimulateCreate,+ logsServicesCreate,} from 'products/logs/frontend/generated/api'import {LogsSamplingRuleApi,@@ -46,6 +47,8 @@ export interface LogsSamplingFormType {severity_error_rate: numberalways_keep_status_gte: stringalways_keep_latency_ms_gt: string+ rate_limit_logs_per_second: string+ rate_limit_burst_logs: string}const DEFAULT_FORM: LogsSamplingFormType = {@@ -67,6 +70,8 @@ const DEFAULT_FORM: LogsSamplingFormType = {severity_error_rate: 0.5,always_keep_status_gte: '',always_keep_latency_ms_gt: '',+ rate_limit_logs_per_second: '',+ rate_limit_burst_logs: '',}function parseSeverityPart(@@ -130,6 +135,14 @@ export function buildSamplingFormDefaults(rule: LogsSamplingRuleApi | null): Log}}}+ if (rule.rule_type === RuleTypeEnumApi.RateLimit) {+ form.rate_limit_logs_per_second =+ typeof cfg.logs_per_second === 'number' && !Number.isNaN(cfg.logs_per_second)+ ? String(cfg.logs_per_second)+ : ''+ form.rate_limit_burst_logs =+ typeof cfg.burst_logs === 'number' && !Number.isNaN(cfg.burst_logs) ? String(cfg.burst_logs) : ''+ }return form}@@ -156,6 +169,18 @@ export function buildSamplingConfigPayload(form: LogsSamplingFormType): Record<s}return out}+ if (form.rule_type === RuleTypeEnumApi.RateLimit) {+ const lps = parseInt(form.rate_limit_logs_per_second.trim(), 10)+ const out: Record<string, unknown> = { logs_per_second: lps }+ const burst = form.rate_limit_burst_logs.trim()+ if (burst !== '') {+ const b = parseInt(burst, 10)+ if (!Number.isNaN(b)) {+ out.burst_logs = b+ }+ }+ return out+ }const always: Record<string, unknown> = {}const sg = form.always_keep_status_gte.trim()if (sg !== '') {@@ -200,6 +225,7 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([actions({scheduleSimulate: true,+ refreshServiceTraffic: true,}),loaders(({ values, props }) => ({@@ -207,7 +233,11 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([null as { estimated_reduction_pct: number; notes: string } | null,{runSimulateNow: async () => {- if (!props.rule?.id || props.rule.rule_type === RuleTypeEnumApi.SeveritySampling) {+ if (+ !props.rule?.id ||+ props.rule.rule_type === RuleTypeEnumApi.SeveritySampling ||+ props.rule.rule_type === RuleTypeEnumApi.RateLimit+ ) {return null}const projectId = String(values.currentTeamId)@@ -215,9 +245,42 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([},},],+ serviceTraffic: [+ null as { log_count: number; avg_logs_per_sec: number } | null,+ {+ loadServiceTraffic: async (_, breakpoint) => {+ await breakpoint(400)+ const form = values.samplingForm+ if (form.rule_type !== RuleTypeEnumApi.RateLimit) {+ return null+ }+ const svc = form.scope_service.trim()+ if (!svc) {+ return null+ }+ const projectId = String(values.currentTeamId)+ const res = await logsServicesCreate(projectId, {+ query: {+ dateRange: { date_from: '-24h', date_to: null },+ serviceNames: [svc],+ },+ })+ const row = res.services.find((s) => s.service_name === svc)+ if (!row) {+ return { log_count: 0, avg_logs_per_sec: 0 }+ }+ const logCount = row.log_count+ const avg = logCount / (24 * 3600)+ return { log_count: logCount, avg_logs_per_sec: avg }+ },+ },+ ],})),listeners(({ actions, props, cache }) => ({+ refreshServiceTraffic: () => {+ actions.loadServiceTraffic(null)+ },scheduleSimulate: () => {if (!props.rule?.id) {return@@ -232,6 +295,7 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([},setSamplingFormValue: () => {actions.scheduleSimulate()+ actions.refreshServiceTraffic()},submitSamplingFormSuccess: () => {actions.scheduleSimulate()@@ -242,35 +306,63 @@ export const logsSamplingFormLogic = kea<logsSamplingFormLogicType>([canSimulate: [() => [(_, props) => props.rule],(rule: LogsSamplingRuleApi | null) =>- Boolean(rule?.id) && rule?.rule_type !== RuleTypeEnumApi.SeveritySampling,+ Boolean(rule?.id) &&+ rule?.rule_type !== RuleTypeEnumApi.SeveritySampling &&+ rule?.rule_type !== RuleTypeEnumApi.RateLimit,],isNewRule: [() => [(_, props) => props.rule], (rule: LogsSamplingRuleApi | null) => !rule],}),afterMount(({ actions, props }) => {actions.resetSamplingForm(buildSamplingFormDefaults(props.rule))- if (props.rule?.id && props.rule.rule_type !== RuleTypeEnumApi.SeveritySampling) {+ if (+ props.rule?.id &&+ props.rule.rule_type !== RuleTypeEnumApi.SeveritySampling &&+ props.rule.rule_type !== RuleTypeEnumApi.RateLimit+ ) {actions.scheduleSimulate()}+ actions.refreshServiceTraffic()}),forms(({ props, values }) => ({samplingForm: {defaults: buildSamplingFormDefaults(props.rule),- errors: (form) => ({- name: !form.name?.trim() ? 'Name is required' : undefined,- path_drop_match_attribute_key:- form.rule_type === RuleTypeEnumApi.PathDrop &&- form.path_drop_match_target === 'custom_attribute' &&- !form.path_drop_match_attribute_key?.trim()- ? 'Enter the log attribute key (e.g. http.route)'- : undefined,- }),+ errors: (form) => {+ const lps = parseInt(form.rate_limit_logs_per_second.trim(), 10)+ const burstRaw = form.rate_limit_burst_logs.trim()+ const burst = burstRaw === '' ? null : parseInt(burstRaw, 10)+ return {+ name: !form.name?.trim() ? 'Name is required' : undefined,+ path_drop_match_attribute_key:+ form.rule_type === RuleTypeEnumApi.PathDrop &&+ form.path_drop_match_target === 'custom_attribute' &&+ !form.path_drop_match_attribute_key?.trim()+ ? 'Enter the log attribute key (e.g. http.route)'+ : undefined,+ scope_service:+ form.rule_type === RuleTypeEnumApi.RateLimit && !form.scope_service?.trim()+ ? 'Select or enter a service name'+ : undefined,+ rate_limit_logs_per_second:+ form.rule_type === RuleTypeEnumApi.RateLimit &&+ (form.rate_limit_logs_per_second.trim() === '' || Number.isNaN(lps) || lps < 1)+ ? 'Enter logs per second (integer ≥ 1)'+ : undefined,+ rate_limit_burst_logs:+ form.rule_type === RuleTypeEnumApi.RateLimit &&+ burstRaw !== '' &&+ (burst === null || Number.isNaN(burst) || burst < lps)+ ? 'Burst must be an integer ≥ sustained rate, or leave empty for default'+ : undefined,+ }+ },submit: async (form) => {const projectId = String(values.currentTeamId)try {const scope_service = form.scope_service.trim() || null- const scope_path_pattern = form.scope_path_pattern.trim() || null+ const scope_path_pattern =+ form.rule_type === RuleTypeEnumApi.RateLimit ? null : form.scope_path_pattern.trim() || nullconst scope_attribute_filters = (props.rule?.scope_attribute_filters ??[]) as PatchedLogsSamplingRuleApi['scope_attribute_filters']const payload = {diff --git a/products/logs/frontend/components/LogsSampling/ruleTypeLabel.ts b/products/logs/frontend/components/LogsSampling/ruleTypeLabel.tsindex 34940ba23cf8..2e681d976dc3 100644--- a/products/logs/frontend/components/LogsSampling/ruleTypeLabel.ts+++ b/products/logs/frontend/components/LogsSampling/ruleTypeLabel.ts@@ -8,7 +8,7 @@ export function ruleTypeLabel(ruleType: RuleTypeEnumApi): string {case RuleTypeEnumApi.SeveritySampling:return 'Drop by severity'case RuleTypeEnumApi.RateLimit:- return 'Rate limit'+ return 'Rate limit by service'default: {return String(ruleType)}diff --git a/products/logs/frontend/components/LogsViewer/Filters/ServiceFilter.tsx b/products/logs/frontend/components/LogsViewer/Filters/ServiceFilter.tsxindex 8a49f13e9bc6..05850e0f6db9 100644--- a/products/logs/frontend/components/LogsViewer/Filters/ServiceFilter.tsx+++ b/products/logs/frontend/components/LogsViewer/Filters/ServiceFilter.tsx@@ -53,14 +53,29 @@ interface ServiceFilterProps {onChange: (serviceNames: LogsQuery['serviceNames']) => void/** When omitted, the backend's default date range is used */dateRange?: DateRange+ /** Single-select replaces the selection on each pick; omit for multi-select (logs viewer). */+ selectionMode?: 'multi' | 'single'+ /** Button label when nothing is selected (single mode only). */+ emptyButtonLabel?: string}-export const ServiceFilter = ({ value, onChange, dateRange }: ServiceFilterProps): JSX.Element => {+export const ServiceFilter = ({+ value,+ onChange,+ dateRange,+ selectionMode = 'multi',+ emptyButtonLabel = 'Pick service',+}: ServiceFilterProps): JSX.Element => {const logicProps: ServiceFilterLogicProps = { dateRange }return (<BindLogic logic={serviceFilterLogic} props={logicProps}>- <ServiceFilterInner value={value} onChange={onChange} />+ <ServiceFilterInner+ value={value}+ onChange={onChange}+ selectionMode={selectionMode}+ emptyButtonLabel={emptyButtonLabel}+ /></BindLogic>)}@@ -68,9 +83,13 @@ export const ServiceFilter = ({ value, onChange, dateRange }: ServiceFilterPropsfunction ServiceFilterInner({value,onChange,+ selectionMode,+ emptyButtonLabel,}: {value: LogsQuery['serviceNames']onChange: (serviceNames: LogsQuery['serviceNames']) => void+ selectionMode: 'multi' | 'single'+ emptyButtonLabel: string}): JSX.Element {const { serviceNames, allServiceNames, allServiceNamesLoading, search } = useValues(serviceFilterLogic)const { setSearch } = useActions(serviceFilterLogic)@@ -79,11 +98,16 @@ function ServiceFilterInner({const onToggle = useCallback((name: string) => {+ if (selectionMode === 'single') {+ const isSelected = selected.includes(name)+ onChange(isSelected ? [] : [name])+ return+ }const isSelected = selected.includes(name)const newNames = isSelected ? selected.filter((n) => n !== name) : [...selected, name]onChange(newNames)},- [selected, onChange]+ [selected, onChange, selectionMode])const rowProps = useMemo<ServiceOptionRowProps>(@@ -98,7 +122,7 @@ function ServiceFilterInner({return (<LemonDropdown- closeOnClickInside={false}+ closeOnClickInside={selectionMode === 'single'}overlay={<div className="space-y-px p-1"><div className="px-1 pb-1">@@ -121,7 +145,7 @@ function ServiceFilterInner({</div>) : (<>- {selected.length > 0 && (+ {selected.length > 0 && selectionMode === 'multi' && (<><div className="flex flex-wrap gap-1 px-1 pb-1 max-w-[300px]">{selected.map((name: string) => (@@ -163,7 +187,9 @@ function ServiceFilterInner({loading={allServiceNamesLoading && selected.length === 0}>{selected.length === 0- ? 'All services'+ ? selectionMode === 'single'+ ? emptyButtonLabel+ : 'All services': selected.length === 1? selected[0]: `${selected.length} services`}diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 5b530e87f646..b8433074dea5 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -866,7 +866,7 @@ export interface LogsSamplingRuleApi {* @nullable*/priority?: number | null- /** Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).* `severity_sampling` - Severity-based reduction* `path_drop` - Path exclusion@@ -886,7 +886,7 @@ export interface LogsSamplingRuleApi {scope_path_pattern?: string | null/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */scope_attribute_filters?: LogsSamplingRuleApiScopeAttributeFiltersItem[]- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved. */+ /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */config: unknown/** Incremented on each update for worker cache coherency. */readonly version: number@@ -923,7 +923,7 @@ export interface PatchedLogsSamplingRuleApi {* @nullable*/priority?: number | null- /** Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).* `severity_sampling` - Severity-based reduction* `path_drop` - Path exclusion@@ -943,7 +943,7 @@ export interface PatchedLogsSamplingRuleApi {scope_path_pattern?: string | null/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */scope_attribute_filters?: PatchedLogsSamplingRuleApiScopeAttributeFiltersItem[]- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved. */+ /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */config?: unknown/** Incremented on each update for worker cache coherency. */readonly version?: numberdiff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 35223fb2089e..bd0a10593413 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -671,7 +671,7 @@ export const LogsSamplingRulesCreateBody = /* @__PURE__ */ zod.object({'* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit').describe(- 'Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'),scope_service: zod.string()@@ -692,7 +692,7 @@ export const LogsSamplingRulesCreateBody = /* @__PURE__ */ zod.object({config: zod.unknown().describe(- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved.'+ 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'),})@@ -724,7 +724,7 @@ export const LogsSamplingRulesUpdateBody = /* @__PURE__ */ zod.object({'* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit').describe(- 'Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'),scope_service: zod.string()@@ -745,7 +745,7 @@ export const LogsSamplingRulesUpdateBody = /* @__PURE__ */ zod.object({config: zod.unknown().describe(- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved.'+ 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'),})@@ -782,7 +782,7 @@ export const LogsSamplingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({).optional().describe(- 'Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'+ 'Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).\n\n* `severity_sampling` - Severity-based reduction\n* `path_drop` - Path exclusion\n* `rate_limit` - Rate limit'),scope_service: zod.string()@@ -804,7 +804,7 @@ export const LogsSamplingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({.unknown().optional().describe(- 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved.'+ 'Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line.'),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f776d3006f30..f135f6380121 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -21588,7 +21588,7 @@ export namespace Schemas {* @nullable*/priority?: number | null;- /** Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).* `severity_sampling` - Severity-based reduction* `path_drop` - Path exclusion@@ -21608,7 +21608,7 @@ export namespace Schemas {scope_path_pattern?: string | null;/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */scope_attribute_filters?: LogsSamplingRuleScopeAttributeFiltersItem[];- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved. */+ /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */config: unknown;/** Incremented on each update for worker cache coherency. */readonly version: number;@@ -28482,7 +28482,7 @@ export namespace Schemas {* @nullable*/priority?: number | null;- /** Rule kind: severity_sampling, path_drop, or rate_limit (rate_limit reserved for a future release).+ /** Rule kind: severity_sampling, path_drop, or rate_limit (caps logs/sec for scope_service at ingestion).* `severity_sampling` - Severity-based reduction* `path_drop` - Path exclusion@@ -28502,7 +28502,7 @@ export namespace Schemas {scope_path_pattern?: string | null;/** Optional list of predicates over string attributes, e.g. [{"key":"http.route","op":"eq","value":"/api"}]. */scope_attribute_filters?: PatchedLogsSamplingRuleScopeAttributeFiltersItem[];- /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. rate_limit is reserved. */+ /** Type-specific JSON. For path_drop: object with required `patterns` (list of regex strings) and optional `match_attribute_key` (string). When `match_attribute_key` is omitted or empty, patterns match the same virtual path string as ingestion (url.path, http.path, http.route, path). When set, each pattern is tested only against that string attribute on the log record. For severity_sampling: object with `actions` per severity level and optional `always_keep`. For rate_limit: object with required `logs_per_second` (integer 1–1000000) and optional `burst_logs` (integer ≥ logs_per_second, max 60000000); rate_limit rules require non-null `scope_service` matching `service.name` on each log line. */config?: unknown;/** Incremented on each update for worker cache coherency. */readonly version?: number;