Inferensys

Prompt

Log Sampling Strategy Decision Prompt

A practical prompt playbook for using the Log Sampling Strategy Decision Prompt in production AI workflows to control cost while preserving forensic capability.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for a log sampling strategy decision prompt.

This prompt is for SREs and platform engineers who need to design a log sampling strategy that balances cost control with the need to retain forensic evidence for debugging, security incidents, and compliance. The ideal user has a defined set of services, a known log volume problem, and specific error paths or security events that must never be sampled out. The prompt helps you produce a structured sampling strategy with rules, rates, and retention policies, rather than a one-size-fits-all percentage.

Use this prompt when you have telemetry data showing unsustainable log volume growth and you need to make intentional trade-offs about what to keep, what to sample, and what to drop. The prompt requires concrete inputs: a list of services, their current log volumes, known high-value log categories (error stacks, authentication events, data mutations), and any compliance or retention requirements. It is not designed for real-time metric generation or trace sampling, which require different statistical models like tail-based sampling or reservoir sampling. Do not use this prompt if you are designing a metrics pipeline, a distributed tracing strategy, or an alerting architecture—those are separate design problems with their own constraints.

Before running this prompt, gather your service inventory, volume estimates, and a list of 'never-sample' events. The prompt will ask you to define sampling rules per service or log category, specify retention windows, and document the rationale for each decision. The output should be a document you can review with your team and implement in your log aggregation pipeline. If your environment is regulated, plan for a human review step before the strategy is applied to production. After you have a strategy, the next step is to implement it in your observability pipeline and validate that critical events are still captured during a controlled rollout.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Log Sampling Strategy Decision Prompt fits your current operational context.

01

Good Fit: Cost-Driven Sampling Design

Use when: You need to reduce log volume for cost control while preserving forensic capability for error paths and security events. Guardrail: The prompt produces a strategy with rules, rates, and retention policies, but you must validate the sampling rates against your actual error budget and compliance requirements before implementation.

02

Bad Fit: Real-Time Anomaly Detection

Avoid when: You need to detect rare events in real time from sampled data. Sampling can drop the very signals you need. Guardrail: Use this prompt for storage and retention strategy, not for designing real-time detection pipelines. Pair with a separate alerting architecture design prompt for the detection layer.

03

Required Input: Service Topology and Traffic Profile

Risk: Without a clear map of services, error paths, and traffic patterns, the sampling strategy will be generic and miss critical coverage gaps. Guardrail: Provide a service dependency map, known failure modes, and traffic volume estimates as input context. The prompt's eval checks depend on this grounding.

04

Operational Risk: Silent Data Loss in Security Audits

Risk: Aggressive sampling can drop security-relevant events, creating blind spots that surface during audits or incident investigations. Guardrail: The prompt includes eval checks for security event coverage. Always review the output against your security monitoring requirements and compliance evidence needs before applying sampling rules.

05

Operational Risk: Sampling Bias in Postmortems

Risk: Sampled logs can mislead root cause analysis by hiding rare but critical event sequences. Guardrail: The prompt should produce a strategy that preserves 100% of error-level and security events. Validate that the output explicitly exempts these event classes from sampling before deployment.

06

When to Escalate: Multi-Tenant or Regulated Environments

Risk: In multi-tenant platforms or regulated industries, sampling decisions can have compliance implications that a prompt alone cannot resolve. Guardrail: Use this prompt as a draft generator. Require human review by security, compliance, and platform engineering before applying sampling rules in production. Document the approval in your observability governance records.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for generating a log sampling strategy that balances cost, forensic capability, and compliance.

This prompt template is designed to be pasted directly into your AI harness. It accepts a description of your system's traffic profile, error characteristics, and business constraints, and returns a structured sampling strategy. The strategy includes specific rules, sampling rates, and retention policies. All dynamic inputs are represented as square-bracket placeholders, such as [SERVICE_PROFILE] and [COST_CONSTRAINTS]. Replace these with your concrete data before execution.

markdown
You are a senior SRE architect designing a log sampling strategy for a production service. Your goal is to minimize log volume and cost while preserving the ability to debug failures, investigate security incidents, and meet compliance requirements.

## Input Data
- **Service Profile:** [SERVICE_PROFILE]
- **Traffic Pattern:** [TRAFFIC_PATTERN]
- **Error Characteristics:** [ERROR_CHARACTERISTICS]
- **Security Event Profile:** [SECURITY_EVENT_PROFILE]
- **Compliance Requirements:** [COMPLIANCE_REQUIREMENTS]
- **Cost Constraints:** [COST_CONSTRAINTS]
- **Current Log Volume (GB/day):** [CURRENT_LOG_VOLUME]

## Output Schema
Return a JSON object with the following structure:
{
  "strategy_name": "string",
  "overview": "string (brief summary of the approach)",
  "sampling_rules": [
    {
      "rule_name": "string",
      "selector": "string (e.g., log level, service, endpoint, error code)",
      "sampling_rate": "number (0.0 to 1.0, where 1.0 means keep all)",
      "rationale": "string (why this rate was chosen)"
    }
  ],
  "retention_policy": {
    "hot_storage_days": "number",
    "cold_storage_days": "number",
    "rationale": "string"
  },
  "forensic_safeguards": [
    "string (specific mechanism to ensure critical events are not lost, e.g., '100% sampling for 5xx errors')"
  ],
  "estimated_cost_savings": "string (qualitative or quantitative estimate)",
  "risks_and_mitigations": [
    {
      "risk": "string",
      "mitigation": "string"
    }
  ]
}

## Constraints
- [CONSTRAINTS]

## Evaluation Criteria
A valid strategy will be judged on these criteria:
1.  **Error Path Coverage:** Does it guarantee 100% capture of server-side errors (5xx)?
2.  **Security Event Coverage:** Does it guarantee 100% capture of defined security events (e.g., auth failures)?
3.  **Cost Reduction:** Does it project a meaningful reduction in log volume?
4.  **Debugability:** Does it preserve enough context (e.g., by sampling entire traces or request paths) to debug a sampled transaction?
5.  **Compliance:** Does the retention policy meet the stated requirements?

Generate the strategy.

To adapt this template, replace each bracketed placeholder with a concise, factual description. The [SERVICE_PROFILE] should describe the service's role and criticality. [CONSTRAINTS] is where you inject hard rules, such as 'Must not sample any logs from the payments service' or 'Use only infrastructure-level sampling agents.' After generating the output, validate the JSON structure and then apply the evaluation criteria manually or with a separate LLM-as-judge step to ensure the strategy is sound before implementation.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Log Sampling Strategy Decision Prompt. Replace each placeholder with concrete values before sending the prompt to the model. Validation notes describe how to check that the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[SYSTEM_ARCHITECTURE]

Describes the services, data flows, and infrastructure boundaries generating logs

Microservices on Kubernetes with Kafka for async messaging and PostgreSQL for persistence

Must be a non-empty string. Check that it names at least two components and their interaction pattern

[LOG_VOLUME_METRICS]

Current or projected log volume in events per second, bytes per day, or similar units

5000 events/sec peak, 2 TB/day uncompressed

Must include a numeric rate and a time window. Parse for digits and unit consistency

[COST_CONSTRAINTS]

Budget limits for log ingestion, storage, and query infrastructure

$15,000/month total observability budget, log storage cannot exceed $6,000/month

Must specify a currency amount and a scope boundary. Check for explicit numeric value

[RETENTION_REQUIREMENTS]

Regulatory, compliance, or business-driven minimum and maximum retention periods

PCI DSS requires 90 days hot, 1 year cold; business needs 30 days hot for debugging

Must list at least one retention period with a reason. Validate that hot retention is shorter than or equal to cold retention

[CRITICAL_EVENT_CATEGORIES]

Event types that must never be sampled out, such as errors, security events, or audit records

ERROR and FATAL log levels, authentication failures, schema validation errors, payment gateway timeouts

Must be a list of at least one event category. Each category should be mappable to a log attribute or pattern

[SAMPLING_CONSTRAINTS]

Hard constraints on sampling, such as minimum rates for specific services or legal prohibitions on sampling certain data

Payment service logs must be 100% retained; all other services can be sampled down to 10%

Must specify per-service or per-category rules. Check for conflicts with [CRITICAL_EVENT_CATEGORIES]

[OBSERVABILITY_STACK]

The logging backend, query engine, and storage system in use or planned

OpenTelemetry Collector to Grafana Loki with S3 cold storage

Must name at least a collector and a storage target. Validate that the stack supports the sampling mechanism being designed

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Log Sampling Strategy Decision Prompt into an SRE workflow with validation, retries, and human approval gates.

This prompt is designed to be called from an internal platform tool or a CI/CD pipeline stage that gates observability configuration changes. The application harness should collect the required inputs—service catalog metadata, traffic profiles, error budget status, and current telemetry costs—from your observability backend (e.g., Grafana, Datadog, Honeycomb) and your incident management system before assembling the prompt. Do not leave these fields to manual copy-paste; stale data produces sampling strategies that either overspend or drop forensic evidence. The harness should also inject a unique request_id and timestamp into the [CONTEXT] block so every generated strategy is traceable to the exact inputs that produced it.

After the model returns a sampling strategy, run a structured output validator that checks for required fields: sampling_rules (each with selector, rate, and rationale), retention_policy, error_path_coverage, and security_event_coverage. If the validator fails, retry once with the validation errors appended to the [CONSTRAINTS] block. If the second attempt also fails, route the request to a human review queue with the partial output and validation log attached. For model choice, use a model with strong JSON mode and long-context support (e.g., gpt-4o or claude-3-opus) because the prompt includes detailed service profiles and cost data that must not be truncated. Set temperature=0.2 to balance consistency with the nuanced trade-offs sampling decisions require.

Log every generation attempt—inputs, outputs, validation results, and the final approved strategy—to an audit table. This is critical because sampling decisions directly affect incident forensics; when a production issue is investigated six months later, the team must be able to explain why certain log streams were sampled at specific rates. Before the strategy is applied to production log pipelines, require a human approval step for any rule that samples error-level logs or security-relevant events at less than 100%. The approval UI should display the generated strategy alongside the input context, the model's rationale, and a diff against the current sampling configuration. Never auto-apply sampling changes without this gate.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required JSON fields, types, and validation rules for the log sampling strategy output. Use this contract to parse, validate, and integrate the model's response into downstream automation or review pipelines.

Field or ElementType or FormatRequiredValidation Rule

strategy_name

string

Non-empty string. Must match pattern ^[a-z0-9_-]+$ for safe use in config keys.

sampling_rules

array of objects

Array must contain at least 1 rule. Each object must pass the sampling_rule schema check.

sampling_rules[].priority

integer

Positive integer. Must be unique across all rules. Lower numbers indicate higher evaluation priority.

sampling_rules[].condition

string

Non-empty string describing the match criteria (e.g., 'level == ERROR', 'service == payment-gateway'). Must be parseable as a boolean expression.

sampling_rules[].sample_rate

number

Float between 0.0 and 1.0 inclusive. 1.0 means keep all matching logs.

sampling_rules[].rationale

string

Non-empty string explaining the forensic or cost justification for this specific rule.

retention_policy

object

Must contain 'hot_days' and 'cold_days' integer fields. 'hot_days' must be >= 1. 'cold_days' must be >= 'hot_days'.

error_path_coverage_check

object

Must contain 'covered_error_paths' (array of strings) and 'uncovered_error_paths' (array of strings). At least one array must be non-empty.

PRACTICAL GUARDRAILS

Common Failure Modes

Log sampling strategies fail silently until a critical event is dropped. These are the most common failure modes when using a prompt to design a sampling strategy, and how to prevent them before they reach production.

01

Sampling Error Paths by Accident

What to watch: The model proposes a uniform sampling rate that applies equally to all traffic, including 5xx errors, security exceptions, and critical transaction failures. This destroys forensic capability for the exact events you need most. Guardrail: Add a hard constraint in the prompt requiring 100% capture for error-level events, authentication failures, and any log with a defined severity above WARN. Validate the output by checking that error paths are explicitly excluded from the sampling rate.

02

Ignoring Trace-ID Correlation Requirements

What to watch: The strategy samples individual log lines without considering that distributed tracing requires all spans in a trace to be sampled or dropped together. Head-based sampling decisions made at the ingress must propagate downstream. Guardrail: Require the prompt output to specify a head-based sampling decision propagated via traceparent headers, and validate that the strategy document explicitly addresses trace completeness, not just log-line completeness.

03

Retention Policy Mismatch with Compliance Needs

What to watch: The model proposes aggressive log rotation or deletion that violates SOC2, HIPAA, or internal retention mandates. It treats cost optimization as the only objective and ignores regulatory minimums. Guardrail: Include [RETENTION_REQUIREMENTS] as a required input field with explicit minimum retention periods per log class. Validate the output retention policy against each requirement before accepting the strategy.

04

Sampling Rate Based on Volume, Not Signal Value

What to watch: The strategy sets sampling rates purely to hit a volume target, without considering that rare but high-value events need higher capture rates. A 1% sample of all traffic loses rare security events entirely. Guardrail: Require the prompt to produce per-category sampling rates based on event rarity and diagnostic value, not just volume. Validate that the output includes a rationale for each rate tied to the event's operational importance.

05

No Dry-Run or Shadow Mode Before Cutover

What to watch: The prompt produces a strategy that assumes immediate production cutover with no validation period. Sampling bugs surface only after logs are already lost. Guardrail: Add a prompt constraint requiring a shadow-mode phase where the sampling logic runs alongside full capture for at least one full business cycle. Validate that the output includes a rollback condition and a comparison checkpoint before final cutover.

06

Cardinality Explosion in Sampled Metric Dimensions

What to watch: The strategy recommends sampling logs but emitting derived metrics with unbounded cardinality, shifting the cost problem from log storage to metric storage without solving it. Guardrail: Require the prompt output to include a cardinality budget for any derived metrics, with explicit limits on label dimensions. Validate that no metric dimension in the output can grow unbounded with traffic or user count.

IMPLEMENTATION TABLE

Evaluation Rubric

Test the Log Sampling Strategy Decision Prompt output quality before shipping. Each criterion validates a critical property of the generated sampling strategy. Use these tests in CI, manual review, or an LLM-as-judge harness.

CriterionPass StandardFailure SignalTest Method

Error Path Coverage

Strategy explicitly samples 100% of ERROR and FATAL level logs

Sampling rule excludes or down-samples error-level events

Parse output for sampling rules; assert rule exists with level IN (ERROR, FATAL) and rate = 1.0

Security Event Coverage

Strategy identifies at least one security-relevant event category (e.g., auth failure, permission denied) and assigns 100% sampling

No security event category mentioned or security events sampled below 100%

Keyword scan for auth, permission, forbidden, token, credential; assert associated sampling rate = 1.0

Cost Constraint Adherence

Total projected log volume under sampling falls within [COST_BUDGET] threshold

Projected volume exceeds budget or budget constraint is ignored

Extract projected volume metric; assert numeric value <= [COST_BUDGET]

Retention Tier Definition

Output defines at least two retention tiers (e.g., hot, cold) with distinct durations and storage targets

Single retention period or no retention policy specified

Parse retention section; count distinct tiers; assert count >= 2 with duration and storage fields present

Sampling Rate Justification

Each sampling rate includes a rationale tied to forensic value, compliance requirement, or cost trade-off

Rates provided without explanation or with generic justifications like 'best practice'

For each sampling rule, assert rationale field is non-empty and contains a domain-specific reason

Downstream System Compatibility

Strategy notes format requirements or constraints for [LOG_CONSUMER] systems (e.g., SIEM, data lake)

No mention of downstream consumers or format mismatches introduced

Keyword scan for [LOG_CONSUMER] or consumer names; assert compatibility note exists

Edge Case Handling

Strategy addresses burst scenarios, storage full conditions, or sampling rate transitions

No mention of edge cases, overload, or degraded operation

Scan for burst, overflow, degraded, fallback, or transition keywords; assert at least one edge case addressed

Schema Consistency

All sampling rules use the same field names and value formats as defined in [LOG_SCHEMA]

Rules reference undefined fields or use inconsistent value formats (e.g., mixed string/integer levels)

Validate rule fields against [LOG_SCHEMA] definition; assert zero undefined field references

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single sampling rule and a simplified output schema. Replace the full [SERVICE_INVENTORY] with a single representative service. Reduce [RETENTION_POLICY] to one tier. Skip cost-model integration and ask for a narrative recommendation instead of structured JSON.

Watch for

  • Over-sampling error logs because the model defaults to "capture everything"
  • Missing the distinction between tail sampling and head sampling
  • No validation that sampled volume fits within a stated [LOG_BUDGET_GB_PER_DAY]
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.