jozef

jozef

Hey everyone,

Trifle.Stats is a library for tracking custom application metrics as time-series data. Orders, revenue, job counts, feature usage. The stuff you keep answering from iex until someone asks for a chart. No separate metrics service, no events table, no pipeline. It writes pre-aggregated rollups into Postgres, MySQL, SQLite, MongoDB or Redis (plus an in-memory Process driver for dev/tests).

It started as a Ruby gem and the Elixir library shares the key structure and storage layout, so a mixed Ruby/Elixir system can write into the same tables and read each other’s metrics.

Both sides are in production use. The Ruby version tracks around 100M background jobs a day at DropBot. The Elixir version runs inside Trifle App, which is an Elixir app itself. There it writes a small amount of usage stats but mostly sits on the read path, serving series for dashboards, alerts, the API and AI analysis. So the write path has been exercised hardest from Ruby, and the read/aggregation path hardest from Elixir.

How it works

You give it a key, a timestamp and a map of values. It increments those values into buckets for every granularity you configured. Setup with Postgres:

{:ok, conn} = Postgrex.start_link(
  hostname: "localhost",
  database: "myapp_stats"
)

# creates tables + indexes
Trifle.Stats.Driver.Postgres.setup!(conn)

Trifle.Stats.configure(
  driver: Trifle.Stats.Driver.Postgres.new(conn),
  time_zone: "UTC",
  track_granularities: ["1h", "1d", "1w", "1mo"],
  beginning_of_week: :monday
)

The interesting part: values is not a single counter. It is a map, and it can be nested. Every numeric leaf gets incremented:

Trifle.Stats.track("orders::completed", DateTime.utc_now(), %{
  count: 1,
  revenue_cents: order.total_cents,
  payment: %{
    order.payment_method => %{count: 1, revenue_cents: order.total_cents}
  },
  channel: %{
    order.channel => %{count: 1, revenue_cents: order.total_cents}
  }
})

One call increments the totals plus the per-payment-method and per-channel breakdowns, in the hourly, daily, weekly and monthly buckets. Lots of tools can count. Counting a whole tree of things in one write is the part I have not seen elsewhere.

On Postgres each bucket is one row (key + granularity + timestamp) with a JSONB payload, and the increment is a single INSERT ... ON CONFLICT DO UPDATE built from nested jsonb_set calls. No read-modify-write in the app.

Reading gives you parallel lists of timestamps and values:

now = DateTime.utc_now()
from = DateTime.add(now, -30, :day)

Trifle.Stats.values("orders::completed", from, now, "1d")
# => %{
#      at: [~U[2026-06-14 00:00:00Z], ...],
#      values: [%{"count" => 128, "revenue_cents" => 1034400,
#                 "payment" => %{"card" => %{"count" => 97, ...}, ...}}, ...]
#    }

Series pipelines

The part that fits Elixir nicely: wrap the result in a Series and everything is pipe-friendly. Aggregators and formatters are terminal operations, transponders derive new values inside the series:

use Trifle.Stats.Series.Fluent

series =
  Trifle.Stats.values("orders::completed", from, now, "1d")
  |> Trifle.Stats.series()

# Total revenue over 30 days
series |> aggregate_sum("revenue_cents")

# Card orders only, dot-path into the nested tree
series |> aggregate_sum("payment.card.count")

# Derive average order value per day, then find the best day
series
|> transpond_expression(["revenue_cents", "count"], "a / b", "aov")
|> aggregate_max("aov")

# Chart-ready output
series |> format_timeline("count")

Notice that “card orders per day” was never declared as a metric anywhere. It just falls out of the data model. Any branch you tracked can be queried later without defining it upfront.

Status pings

Besides time series there is a small status API. beam/3 overwrites the latest state for a key, scan/1 reads it back. Named after submarine sonar, because naming things is hard:

Trifle.Stats.beam("worker::sync", DateTime.utc_now(), %{count: 5, duration: 12})
                                                                                      Trifle.Stats.scan("worker::sync")                                                                                                                                     # => {:ok, %{...}}

Useful for “when did this worker last run and what did it do” without paying for a full time series.

What it is not

It stores pre-aggregated rollups, so you decide what to count at write time, not query time. If you need raw event replay, ad-hoc queries over dimensions you did not track, or user-level analytics, this is not that tool. It is deliberately simple. That is kind of the whole point.

Current version is 2.5.0, MIT licensed. Feedback very welcome, especially on the driver implementations and what you would want from the Series API.

Docs: Trifle.Stats | Trifle Docs
Hex: trifle_stats | Hex

Where Next? Top

Trending in Announcing Top

bluzky
You may know https://ui.shadcn.com/, a UI component library for React. I really love it’s design style and components. I’ve built some co...
387 15136 120
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
restlessronin
The repo is at GitHub - cyberchitta/openai_ex: Community maintained Elixir library for OpenAI API · GitHub. Docs are at OpenaiEx User Gu...
152 11030 135
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
shahryarjb
The Chelekom project is a library of Phoenix and LiveView components generated via Mix tasks to fit developer needs seamlessly. One of i...
New
woylie
Phoenix components for pagination, sortable tables and filter forms with Flop and (optionally) Ecto. pagination cursor pagination sorta...
New
kip
Please say hi to a new lib, Astro that aims to deliver easy-to-consume astronomy calculations of practical use. For now it only calculat...
New

Other Trending Topics Top

akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
bartblast
Hey folks, I just published a post about Hologram’s funding and where the project goes next - the short version: Curiosum as Main Spons...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
mudasobwa
I am seeing a lot of aplications of Argumentum ad Vericundiam in software discussions. They do link some piece of writing and point us to...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews