Architecture & developer guide · v0.1.0

Distill

A Rust service for structured logs and aggregates.

View on GitHub ↗

Applications send events to named channels. Each channel decides which events retain their full detail, how the stream is summarized, and where the results are stored.

Rust / Tokio / AxumRabbitMQ.NET / AspireSelf-hosted · MIT

One channel · warning threshold · count

orders.production

Structured events from your applications

Illustrative severity routing
LevelPolicy

Trace → Info

Contribute to the count

Individual detail is not stored in the sink

Warning → Critical

Count + full event

Preserve the payload and context

Every event counts, including errors. Remove the aggregator to store every event individually.

For application developers

Keep structured logging; declare the storage policy once per channel version.

For operating a service

Retain incident detail alongside summaries of repetitive traffic.

For the data owner

Write to PostgreSQL, MySQL, SQL Server, or a conforming HTTP receiver. Query results there.

Where the responsibilities sit

HTTP adapters translate requests. Channel actors own processing state. RabbitMQ holds delivery work; SQLite holds recovery state; the configured sink holds the results.

Produce

Application

JSON · Protobuf OTLP/HTTP JSON · .NET

Adapt

Axum HTTP

Authentication, limits, decoding and validation

Classify

Channel actors

Explicit name + version Bounded mailboxes

Durable admission

RabbitMQ

Publication confirmed before acceptance

After admission: consumers process the declared routes

Persist the event with its stable identity. Acknowledge after the write succeeds.

Commit the source ID and updated window together, then acknowledge the input. At flush, commit the snapshot and pending output together; publish it for sink delivery.

Accepted = broker-confirmed admission. The sink write can still be pending.

Recovery requires retained broker data and the private SQLite state volume.

Reading results uses your sink’s tools. Distill has no built-in log-search UI.

RabbitMQ is a delivery boundary, not the final log store. SQLite stores configuration, duplicate history, checkpoints, and pending aggregate outputs.

Implementation responsibilities and the reason for each boundary
AreaOwnsWhy this boundary helps

Domain contracts

Events, channels, aggregate specifications

Shared data contracts stay separate from HTTP and storage drivers.

Channel processing

Routing, actors, aggregation, schemas, recovery

A channel’s mutable window has one owner; policy and recovery can be exercised directly.

Broker delivery

Publication, consumers, retries, dead letters

Delivery failures and acknowledgements follow one broker protocol.

Storage adapters

Sink contract and four drivers

Drivers share event and aggregate write semantics; the core does not need SQL dialect logic.

HTTP API and configuration

API adapters; process settings and CLI

Transport details and deployment settings have distinct places to change.

.NET integrations

Client, ILogger provider, Aspire integration

Direct API users do not need the logging provider or orchestration package.

Declare a policy. Send an event.

This example counts checkout activity and keeps warnings and errors intact. It assumes a running Distill instance and a registered sink named primary.

1 Create an immutable channel version

Private admin · POST /channels
{
  "name": "checkout.requests",
  "version": "1",
  "sink_id": "primary",
  "preset": "errors_only",
  "aggregator": {
    "function": "count",
    "granularity": "per_t_time",
    "parameter": 60
  }
}

The preset sets the threshold to warning. The override changes its default five-minute count to 60 seconds. Identical declarations can be repeated; changed content requires a new version.

2 Write through the channel-bound endpoint

Public ingest · shell
curl "$DISTILL_URL/channels/checkout.requests/events" \
  -H "X-API-Key: $DISTILL_INGEST_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "version": "1",
    "severity": "error",
    "message": "Payment authorization failed",
    "attributes": {
      "order_id": "ord-123",
      "provider": "payments-a"
    },
    "metadata": { "trace_id": "trace-abc" }
  }'

This event contributes to the count and is stored individually. The server supplies an ID and timestamp when omitted. For retry safety, supply stable values and reuse the original event.

Setup and validation requests

Start with docker compose up --build or podman compose up --build. Compose supplies Distill, RabbitMQ, and a TLS proxy; it supplies no sink. The admin listener is private to the Distill container. Run provisioning there or through a deliberately configured private network path. The localhost proxy certificate needs local trust.

For a native database, migrate its schema first: distill sink migrate primary --file sinks.json. Alternatively, register a conforming HTTP receiver with POST /sinks; private receiver hosts must pass DISTILL_SINK_ALLOWLIST.

Private admin · shell · run where the listener is reachable
# Save the channel JSON above as channel.json.
curl "$DISTILL_ADMIN_URL/channels" \
  -H "X-API-Key: $DISTILL_ADMIN_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @channel.json

# Use /channels/validate instead to validate without creating.
# Preview routing without enqueueing an event:
curl "$DISTILL_ADMIN_URL/channels/checkout.requests/test" \
  -H "X-API-Key: $DISTILL_ADMIN_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"version":"1","severity":"error","message":"Example"}'

Use the configured URLs and credentials for each listener. Provision sinks through the private admin API before declaring their channels, or supply an optional startup manifest. Runtime registrations persist in SQLite; manifest changes take effect at restart. Database schemas still need explicit migration.

Optional startup sink manifest · sinks.json
{
  "default_sink_id": "primary",
  "sinks": [
    {
      "sink_id": "primary",
      "driver": "postgres",
      "connection_string_env": "DISTILL_POSTGRES_URL"
    }
  ]
}

Set DISTILL_SINKS_CONFIG_PATH to the manifest path and provide DISTILL_POSTGRES_URL in the service environment. Use connection_string_file for a mounted secret instead. Keep database credentials out of committed manifests.

Use existing .NET logging code

AddDistillClient registers the client, logging provider, and readiness check. Aspire’s WithReference(distill) supplies the endpoint and key. Reconcile the finite channel set before serving traffic.

For numeric aggregation, use the structured property value. The metrics preset averages payload.value over 60 seconds and also retains error-level events.

Application Program.cs · abbreviated
builder.AddDistillClient("distill", options =>
    options.DefaultChannel = "checkout.latency");

var app = builder.Build();
var client = app.Services.GetRequiredService<DistillClient>();
await client.ReconcileChannelAsync(new CreateChannelRequest
{
    Name = "checkout.latency", Version = "1",
    SinkId = "primary", Preset = ChannelPreset.Metrics
});

app.Logger.LogInformation("Checkout took {value} ms", 184);
app.Run();
Aspire hosting and other configuration choices
AppHost · local PostgreSQL example
var database = builder.AddPostgres("pg").AddDatabase("distill-db");
var distill = builder.AddDistill("distill")
    .WithLocalBuild()
    .WithSink(database, name: "primary")
    .WithEnvironment("DISTILL_AUTO_MIGRATE", "true"); // local development

builder.AddProject<Projects.Checkout>("checkout")
    .WithReference(distill);

Adapted from DistillTesting. The AppHost needs a UserSecretsId so generated credentials survive local runs with retained volumes. Production uses explicit database migrations. The integration manages RabbitMQ and persistent state; WithLocalBuild uses the repository’s Dockerfile.

Common channel configuration choices
NeedConfiguration

Keep every event

raw_events or audit; no aggregator.

Count routine events; keep warnings

errors_only; default count window is 300 seconds.

Measure a numeric value

metrics averages payload.value; override the function with sum, min, or max.

Keep counts only below Info

count also stores Info and higher individually. Override the threshold to summarize ordinary Info traffic.

Validate stable payload contracts

Attach a runtime Protobuf descriptor to the immutable channel version.

A fleet’s activity, without every routine record

Suppose checkout instances share one count channel. All requests contribute; only errors retain full detail. Adjust the workload to compare final sink records.

Store every event60,000 records
Count + error detail61 records
99.90%

fewer final sink records in this model

60 full error events + 1 aggregate containing all 60,000 contributions.

Illustrative arithmetic, not a benchmark. Assumes a 0.1% error rate (rounded up), one shared channel/version, one completed non-rolling count window, and no early buffer/TTL flush. Threshold is error; no warnings are modeled.

Formula: events = instances × rate × seconds; retained records = ⌈events × 0.001⌉ + 1. This counts final event/aggregate records, not bytes, broker traffic, SQLite duplicate history, or write operations. Every source event still enters the durable path.

Default example: 40 instances × 25 events/second × 60 seconds. Enable JavaScript to adjust it after WebAssembly starts.

Practical uses in a distributed application
Operational questionChannel policyWhat a developer can investigate

Did traffic drop, or did failures rise?

Count checkout requests; retain error events with service, provider, and trace identifiers.

Compare total activity across windows, then inspect preserved failures for shared context.

Did a rollout increase latency?

Average payload.value in milliseconds; use separate channels per deployment cohort.

Compare cohort means and retained slow-request warnings. A mean does not provide p95 or p99.

Are workers completing useful work?

Sum processed-item values in one channel; count completion events in another.

Distinguish fewer completed jobs from smaller job sizes. Preserve failures for retries and diagnosis.

Aggregation is per channel/version, with one function per channel; arbitrary metadata does not create separate groups. Route by region or cohort explicitly. Correlation IDs help connect retained events; they do not reconstruct routine events that were summarized.

The decisions behind the behavior

The strongest engineering work is at the failure boundaries: when admission succeeds, what a retry means, and which state must survive a restart.

Confirm admission before reporting success

A single routed event is published to RabbitMQ before the request is accepted. Delayed sink writes do not require the producer to keep the request open.

Cost: a broker dependency and confirmation latency on ingestion. Acceptance promises queued work, not an immediately queryable row.

Commit contributions before acknowledging inputs

SQLite records the source ID, content fingerprint, and updated aggregate window in one transaction. A redelivered input can be recognized after process replacement.

Cost: local durable state and duplicate-history growth. The broker and SQLite volumes are both part of recovery.

Deliver cumulative snapshots with revisions

Rolling outputs have stable IDs and increasing revisions. Sinks accept identical retries, ignore stale revisions, and reject conflicting content at the same revision.

HTTP receivers must implement this contract atomically; a generic webhook is insufficient. Rolling means an expanding series, not a sliding time window.

Make configuration identities immutable

Applications can register sinks and reconcile channel versions at startup. Explicit producer versions coexist, so a rollout can keep the old policy active while introducing a new one.

Changed definitions need a new version. Version retirement and cross-version merging are not automatic.

Bound overload instead of accumulating indefinitely

Mailboxes, buffers, process memory accounting, and broker queues have limits. Full broker queues reject publication; delayed retries live in durable queues rather than sleeping in the consumer.

Producers must handle failed admission. Exhausted deliveries remain in a dead-letter queue for investigation.

Separate administration from event ingestion

The public router exposes ingestion and operational endpoints. Sink and channel management use a separate private listener. HTTP sinks apply outbound destination checks; native schemas use explicit migrations.

Operators must provide a private provisioning path. Shared API keys do not supply per-client identity or channel-level permissions.

  1. Failure example · 1

    Sink writes revision 7

    The acknowledgement is lost. Distill cannot assume the write failed.

  2. 2

    The same snapshot returns

    A durable retry carries the same aggregate ID, revision, and content.

  3. 3

    The sink accepts the duplicate

    It leaves the stored result unchanged instead of adding the count again.

  4. 4

    Delivery completes

    The consumer acknowledges the message. A later stale revision cannot overwrite revision 7.

Testing and current limits

Tests check event delivery, aggregate correctness, and restart recovery across the service, RabbitMQ, storage drivers, and .NET clients.

What the tests cover

  • Recovery and failure injection Broker tests cover in-flight restart, duplicate inputs, queue overflow, retry isolation, and controlled shutdown.
  • One persistence contract, four implementations Real-service tests check duplicate writes, newer/stale snapshots, conflicting revisions, and final persisted values.
  • A client that accounts for application behavior Provider checks cover burst draining, partial retries, overflow reporting, immutable enqueue snapshots, and bounded disposal.
  • Distribution and operations are included Fresh package-consumer tests, explicit migrations, readiness, metrics, and protected dead-letter inspection accompany release workflow gates.

Results and remaining work

  • Recorded local qualification · 7 November 2026 Recorded local results report 59 Rust unit tests, four external sink contracts, .NET contracts, and package-consumer checks passing. These are recorded results, not a live CI badge.
  • One active Distill instance per broker vhost Distributed producers are supported; active replication of the logger is deferred. SQLite WAL requires compatible persistent local storage.
  • Production-target validation is outstanding Hosted release evidence and actual Aspire/Azure deployment compatibility remain unverified. Local integration workloads establish no sustained-throughput SLA.
  • A focused processing service No full-text search interface, percentile aggregation, automatic retention/compression, or multi-tenant access model is implemented in V1.

Consumer example · DistillTesting / Blazor + Aspire

The application owns its channels

The inspected AppHost supports PostgreSQL, an HTTP receiver, or a reference to an existing Distill instance. The Blazor application reconciles versioned counter and weather channels before startup. Counter events use the SDK; weather measurements use ILogger with {value}.

Recorded qualification runs two producer versions, forces logger and broker restarts, and checks exact persisted aggregates after recovery. Five counter clicks produced count 5, sum 15, average 3, minimum 1, and maximum 5.