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

woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
woylie
I released Doggo, a collection of unstyled Phoenix components. https://github.com/woylie/doggo Features Unstyled Phoenix components....
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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
anuaralfetahe
Hello Published a new library - ProcessHub! ProcessHub is a library designed to manage process distribution within the Elixir cluster. ...
New
rodloboz
I’ve started working on a new library to run SQL queries and do basic business intelligence. Think “Blazer for Elixir.” Currently it fe...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
AstonJ
This showed up on my feed.. anyone heard of it? Just hype? Ox Alpha is a reasoning model designed for coding, sustained ag...
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
CodeSync
:microphone: ElixirConf 2026 - Call for Talks is open! We’re heading to Chicago :united_states: :round_pushpin: In person + virtual :d...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews