How Plausible Analytics Community Edition is built
By Flavio
Tagged: Database
I read the Plausible Community Edition code to see how its tracker, Elixir app, databases, and React dashboard work together.
I use Plausible Analytics on all my sites.
I like it because the dashboard is simple. You open one page and see visitors, sources, pages, countries, and devices.
But I never looked closely at how it worked.
This is the first post in a new series where I open popular software projects and trace how they’re built. I don’t want to just list the technologies they use. I want to read the code and understand how the pieces work together.
We’ll start with Plausible Analytics.
This post is only about Plausible Community Edition, the open-source version you can run yourself. I read the v3.2.1 application source and the matching Community Edition deployment repository.
The server is released under AGPLv3-or-later, while the tracker you add to a website has a separate MIT license.
I followed a pageview from the JavaScript tracker all the way to the dashboard, and I checked how the official Docker setup runs it.
If you’re upgrading a long-untouched self-hosted instance instead, that story is in Updating self-hosted Plausible Analytics using AI.
I ignored Plausible Cloud and its private features. This post is about the code we can read and run ourselves. Plausible changes often, so file names and implementation details will shift over time, though the broader architectural ideas should hold up longer.
What can we learn from this?
I found 10 ideas worth keeping. The architecture matches the work the product does: analytics takes in lots of small events and runs big aggregate reports over them. Plausible keeps the collection script small by compiling away optional features, and it cleans browser input before the rest of the app touches it.
Small in-memory caches avoid repeated database work. The processing pipeline follows a clear order: check, filter, add information, identify, and save. Events from one visitor are processed in order and then grouped into fewer ClickHouse inserts.
Privacy goes all the way down to the storage layer. Plausible doesn’t store raw IP addresses, and temporary visitor IDs change with a rotating salt. The dashboard queries useful metrics like visitors and bounce rate instead of exposing raw database tables.
They only add extra complexity where it helps. React handles the interactive dashboard, Phoenix and LiveView handle the rest, and the official deployment is still just three containers.
What are we looking at?
Plausible is a privacy-friendly web analytics product.
A small JavaScript file runs on a website, watches for pageviews and optional interactions, and sends compact events to Plausible. From there, Plausible filters and enriches those events, groups them into sessions, stores them, and answers aggregate questions for the dashboard.
Mostly, Plausible answers aggregate questions over large collections of events rather than retrieving individual records by ID:
- how many visitors arrived today?
- where did they come from?
- which pages did they read?
- how many visits bounced?
- how long did people stay?
- how does this week compare with last week?
Those questions shape almost every important technical decision in the project.
The architecture in one picture
You might expect Plausible to be a React dashboard with a small API behind it, but the main application is a modular Elixir and Phoenix monolith. It uses Postgres for application data and ClickHouse for analytics data. The interactive dashboard is built with React, while the rest of the web application mostly uses server-rendered Phoenix pages and LiveView.
A separate, small JavaScript tracker runs on each website.
The main flow looks like this:
Postgres sits beside the event path, storing users, sites, settings, permissions, salts, and background jobs.
This split between Postgres and ClickHouse is the first big architectural decision:
Plausible doesn’t ask one database to be both a normal application database and a high-volume analytics engine.
The repository is several systems living together
The top-level directories tell us a lot:
analytics/
assets/ React dashboard and other browser assets
config/ Phoenix and runtime configuration
e2e/ browser-level tests
lib/ Community Edition Elixir application code
priv/ migrations, static data, compiled tracker files
test/ Elixir tests
tracker/ tracker source, compiler, and browser tests
The main mix.exs file describes an Elixir 1.18 application using Phoenix 1.8, Ecto, Postgrex, an Ecto adapter for ClickHouse, Oban, Phoenix LiveView, OpenTelemetry, PromEx, and Sentry.
The browser side includes React, React Router, TanStack Query, Alpine.js, Chart.js, and D3-related packages.
That list could make the application sound more fragmented than it is. There’s still one main Phoenix application, and each tool has a clear job inside it:
- Phoenix handles HTTP, routing, controllers, templates, and the application shell.
- LiveView handles interactive server-rendered product pages.
- React owns the analytics dashboard.
- Alpine.js adds small interactions elsewhere.
- Ecto expresses queries and schemas for both Postgres and ClickHouse.
- Oban runs durable jobs backed by Postgres.
- The BEAM runtime provides supervised processes, caches, workers, and message passing.
Which source belongs to Community Edition?
The Community Edition deployment and the application source live in two repositories. plausible/community-edition contains the official Compose file and the ClickHouse configuration needed to run the app, while the application itself comes from plausible/analytics.
When Plausible builds Community Edition, Mix uses the ce environment. The build compiles lib/ and leaves extra/lib/ out of the release.
The Plausible module has compile-time on_ce and on_ee branches. For this article, I followed the on_ce branch and ignored the other one.
That matters when you’re reading the source: finding a module in the repository doesn’t mean it runs in Community Edition, so you have to check the ce build branch and the official CE configuration.
Start at the browser: the tracker is a tiny application
The tracker lives in the tracker directory.
Its job is small:
- detect a pageview or custom event (set those goals up from the terminal)
- collect the URL, referrer, site domain, and optional properties
- send the event to
/api/event - send engagement time and scroll depth when needed
Because the tracker runs on someone else’s website, it has to be small, fast, and careful not to break the page.
The payload is intentionally compact
A pageview payload has this general shape:
{
"n": "pageview",
"u": "https://flaviocopes.com/react/",
"d": "flaviocopes.com",
"r": "https://google.com/",
"v": 35
}
The fields stand for event name, URL, site domain, referrer, and tracker version.
Short keys aren’t pleasant API design for humans, but they’re good wire design for a script sent and executed on many pages. The server accepts readable versions too, while the browser sends the smaller format.
Why the tracker sends text/plain
The networking module serializes the event as JSON and sends it with the Fetch API:
fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
keepalive: true,
body: JSON.stringify(payload)
})
The old compatibility build can use XMLHttpRequest instead.
Sending text/plain avoids an extra CORS preflight request in normal cases, and keepalive: true gives the browser permission to finish a small request while the page is unloading.
Delivery still isn’t guaranteed: the page can close, the network can fail, or a content blocker can stop the request.
The tracker knows when not to run
The tracker refuses to collect some traffic before making a request. It can ignore:
localhostandfile:pages unless local collection is explicitly enabled- browsers with automation markers such as WebDriver or Cypress
- a browser where
localStorage.plausible_ignoreis set - pages excluded by the site’s configuration
Server-side filtering still runs too, so this first check just avoids sending traffic that’s clearly unwanted.
Pageviews in a single-page application
A traditional page load starts the tracker again on its own. A single-page application changes routes without loading a new document, so Plausible has to observe navigation.
The tracker watches history.pushState(), popstate, and optional hash changes so it can record navigation without a full page reload.
Engagement is active time, not wall-clock time
Plausible does more than record that a page opened. The engagement code counts time only while the page is visible and focused, so it doesn’t count 45 minutes because someone left a tab open in the background.
The tracker sends an engagement event when there’s useful new information: either scroll depth increased, or at least three seconds of additional engagement accumulated.
It also measures scroll depth and updates its idea of the page height whenever the document changes. Even a familiar metric like “time on page” depends on decisions like those.
Custom events are several browser behaviors
Depending on its configuration, the tracker can recognize:
- outbound link clicks
- file downloads based on a list of extensions
- form submissions
- elements tagged with Plausible event classes
- custom events pushed through its public API
The tracker also provides a queue. A page can call the public Plausible function before the full tracker has loaded. The temporary function stores those calls, and the tracker drains them after initialization.
One tracker source becomes more than 1,000 builds
This was the first surprise I found in the code.
Plausible has to support its normal web snippet, an npm package, installation checking, and a bunch of old script URLs that can’t suddenly stop working. On top of that, sites pick different optional features: outbound-link tracking, file downloads, forms, hash routes, or automatic pageviews.
Shipping every feature to every site would bloat the default script, and maintaining a hand-written file for every combination isn’t realistic. So Plausible generates all the variants from one source tree.
As the tracker architecture document describes, Rollup builds the script and SWC strips out the parts a specific variant doesn’t need. Over 1,000 variants compile in roughly three seconds on a development machine.
If a build sets automatic form tracking to false, the compiler removes the form-tracking branch completely instead of leaving an if statement that always fails at runtime.
Backward compatibility becomes a routing problem
Older Plausible installations use script names that encode features right in the filename. The Phoenix TrackerPlug handles those routes by normalizing aliases, sorting the requested feature names, and mapping them to a compiled legacy variant.
Legacy scripts can be cached for a day because their filenames point to immutable behavior. The newer route uses a site-specific script ID instead, so the response can embed a tiny configuration for that site and uses a shorter cache lifetime.
Site configuration is injected without another request
The PlausibleWeb.Tracker module reads the compiled tracker template and injects a compact site configuration right into it. That configuration can include:
- the domain
- the event endpoint
- outbound-link tracking
- file-download tracking
- form tracking
Because the script response is already tailored to the site, the browser doesn’t have to load a generic tracker and make a second request for its settings.
Community Edition warms an in-memory cache of these complete site-specific scripts, with a background warmer refreshing all entries periodically and recently changed sites more often. When you change a setting, Plausible updates the cached script, so the next browser request gets the new configuration without adding an extra endpoint to every page load.
The event endpoint is small on purpose
The public route is POST /api/event. I expected this controller to be packed with logic, but it isn’t.
The ExternalController only does three things:
- cleans up the incoming request
- passes it to
Plausible.Ingestion.Event.build_and_buffer/1 - returns a response
A valid event gets 202 Accepted and ok, and many deliberately dropped events get 202 too. The response can include an x-plausible-dropped header, but a bot or blocked request doesn’t get a detailed public explanation or a retryable error.
That makes sense for an analytics endpoint. If every filtered request returned an error, well-behaved clients might keep retrying traffic the server explicitly doesn’t want, and the endpoint would give away more of its filtering rules. Malformed input is handled differently: a request that can’t become a valid event gets a client error.
Plausible checks the event before using it
The Plausible.Ingestion.Request module uses Ecto to validate the incoming data, even though it isn’t backed by a Postgres table.
The request builder:
- limits the request size
- limits URLs and referrers to 2,000 bytes
- limits an event name to 120 characters
- parses and sanitizes the hostname, path, and query string
- validates engagement fields
- clamps scroll depth to the range from 0 to 100
Custom properties go through another defensive pass. Plausible accepts at most 30, and it strips out nested objects, lists, and blank values.
Anyone can hit the event endpoint, and it handles a lot of traffic, so you don’t want raw browser data leaking deep into the app. Once this step finishes, the rest of the pipeline only deals with a clean event and known fields.
One request can represent several configured domains
The domain field can hold a comma-separated list. Plausible parses the request once and can fan out one event for each configured domain.
Plausible avoids querying Postgres for every event
For every incoming event, Plausible has to check whether the site exists, whether collection is allowed, and which rules apply. Querying Postgres several times per pageview would get expensive fast as traffic grows, so Plausible relies on warmed in-memory caches instead.
Site.Cache holds the site fields needed during ingestion, and background processes keep it fresh. GateKeeper checks that cached site and can reject traffic when:
- no site exists for the domain
- the site isn’t in a collectable state
- ingestion has been disabled for the site
- the site’s traffic exceeds its allowed rate
Hostname, page, IP, and country rules have warmed caches too. Postgres stays the source of truth, without the event endpoint having to query it on every pageview.
The flow looks like this:
Postgres is the source of truth
│
│ periodic and change-driven refreshes
▼
in-memory read model
│
│ constant-time request checks
▼
event processing
The tradeoff is a short delay before a configuration change reaches the cache. That’s completely fine for an analytics setting, even if you wouldn’t accept it for something like revoking access to a bank account.
The event processing code is easy to follow
The real event policy lives in Plausible.Ingestion.Event. This was my favorite part of the codebase to read.
The module lists the processing steps in order:
Each step takes the event and either adds data to it or drops it, and as soon as a step drops it, reduce_while halts the pipeline. That order makes the dependencies obvious: location lookup runs before the country rule because the rule needs the country, the visitor ID is computed after Plausible loads the salt, and ClickHouse validation runs before saving the session.
Because everything flows through the event object, you can tell what the code knows at every point. The pipeline wraps each step with duration telemetry too, and dropped or buffered events emit telemetry with the site, reason, tracker version, and request timestamp. Compared to one giant controller full of nested conditions, it’s much easier to read.
Filtering is layered
The browser skips obvious local or automated traffic first, and then the server applies site rules, checks known spam referrers, and parses the user agent.
Plausible limits browser detection work
User-agent parsing can get expensive, so Plausible caches the results and cuts parsing off after 200 milliseconds. That keeps a weird user-agent string from tying up a request for too long.
The parsed result identifies the browser, operating system, and device, and drops known bots and headless Chrome traffic.
Plausible uses the IP address but does not keep it
Plausible uses the IP address during the request to look up the country, region, and city, then discards it. Neither the ClickHouse event schema nor the session schema has a raw IP address column.
Source attribution has a precedence order
The source resolver checks campaign parameters like utm_source first. If there’s no campaign value, it falls back to the external referrer.
Click identifiers such as gclid, gbraid, wbraid, msclkid, fbclid, and twclid flag advertising traffic and help infer a medium. Keeping this logic on the server lets Plausible improve attribution without shipping an update to every tracker.
How Plausible recognizes a visitor without cookies
Plausible doesn’t store a persistent visitor ID in a cookie. Instead, it builds a temporary ID on the server from values including:
- the browser user agent
- the IP address
- the Plausible site domain
- the visited root domain
- a secret salt
Those values go through a hash function and turn into a number. Conceptually, it looks like this:
temporary_user_id = hash(
daily_secret,
user_agent + ip_address + site_domain + root_domain
)
The raw IP address gets used during the request for filtering, location lookup, and this hash, and never becomes a column in the ClickHouse event or session schemas.
The salt rotates every day
The Session.Salts process keeps both the current and previous salts in memory, backed by Postgres so they survive a restart. An Oban job rotates the salt every day and deletes old salts after 48 hours.
Keeping the previous salt around handles visits that cross midnight. Say a visitor opens a page at 23:59 and clicks a link at 00:01. The second request produces a different ID under the new salt, so Plausible also hashes with the previous salt and checks for an active session under that ID. That keeps the single visit intact without turning the hash into a long-lived identifier.
This is intentionally approximate
Two people behind the same IP with the same user agent can end up with the same temporary ID, and one person switching networks or browser settings will get a new one.
Plausible is estimating visitors rather than building permanent user profiles. Events from the same browser can be grouped into one visit, while the rotating salt stops that ID from following someone across months. Because the database never stores a persistent identity in the first place, privacy is built directly into the storage model.
Plausible keeps active sessions in memory
Plausible considers events part of the same session when they share the temporary user ID and arrive within 30 minutes.
At first, I thought this would be a database query:
- find the latest session for this user
- check its timestamp
- update it or insert a new one
But ClickHouse is built for batches and reports, not for updating a live session on every pageview. So Plausible keeps active sessions in memory instead.
One of 100 workers owns each user
The BalancerSupervisor starts 100 session workers (GenServers in Elixir).
A temporary user ID always routes to the same worker, and that worker processes one message at a time. That way, two events can’t modify the same session concurrently.
Each call has a one-second timeout. If the worker can’t respond in time, Plausible drops the event instead of leaving the request hanging.
What is stored in the active-session cache?
Each active session stores fields like:
- session ID and temporary user ID
- start and last-event timestamps
- entry and exit pages
- total events and pageviews
- duration
- bounce status
- source, referrer, and campaign values
- country, region, and city
- browser, operating system, and device type
The cache removes sessions after 30 minutes. It checks both the current and previous visitor IDs so a visit can cross midnight.
Engagement events cannot create sessions
An engagement event updates scroll depth or time for an existing visit. If it arrives without an active session, Plausible drops it with no_session_for_engagement.
An engagement ping says “the existing page is still active.” It shouldn’t invent a new visit just because the original pageview was blocked, lost, too old, or already expired from the session cache.
How bounce and duration change
A new pageview session begins as a bounce unless the event is already considered interactive.
A second pageview or an interactive custom event can clear the bounce state. Duration becomes the difference between the current event timestamp and the session start. The entry page stays fixed, while the exit page updates as new pageviews arrive.
Keeping the active session in memory makes these updates fast.
How Plausible updates a session in ClickHouse
Plausible writes session updates to the sessions_v2 table, which uses ClickHouse’s VersionedCollapsingMergeTree. Whenever a session changes, Plausible inserts two rows: the old version with a -1 sign, and the new version with a +1 sign. Later, ClickHouse combines those rows and keeps only the latest session.
The live session stays in memory, while ClickHouse receives a history of changes as inserts, which is the kind of write workload it handles well.
The tradeoff is more complex report queries, since old and new versions can both exist in the table until ClickHouse combines them.
Community Edition saves events inside the Phoenix app
Once Plausible checks an event and adds the extra information, it needs to save it. Community Edition handles this inside the same Phoenix app through the Embedded persistor.
Its job is short:
- send the event to the session cache
- create or update the session
- copy session fields onto the event
- add session rows to the session buffer
- add the enriched event to the event buffer
There’s no message broker or separate event service in the official setup. Phoenix receives the request, Elixir holds the active session in memory, and two small buffers batch the rows for ClickHouse.
That’s also why active sessions live right beside the web endpoint: the process handling an event can talk to the in-memory session workers directly.
Events and sessions enter separate write buffers
Plausible doesn’t issue one ClickHouse insert per event. Instead, one buffer collects events and another collects session changes.
By default, a buffer flushes when either condition is reached:
- about 100,000 bytes have accumulated
- five seconds have passed
Rather than making one database request per pageview, Plausible writes many rows at once.
What does 202 Accepted really mean?
In Community Edition, the controller returns as soon as the event is cast to an in-memory buffer. It doesn’t wait for ClickHouse to write the row to disk.
So 202 Accepted means the app accepted the event and placed it in the save queue, not that it’s durably stored on disk and safe from an immediate machine failure.
The buffer tries to flush during a normal shutdown, though a sudden machine failure can still lose whatever is in the current batch. That’s an acceptable tradeoff for web analytics, whereas you wouldn’t want 202 to work that way for a payment, an order, or a medical record where acknowledging a request has to mean the data is already safely persisted.
Why Plausible uses ClickHouse for traffic data
Web analytics produces many writes and a particular kind of read. The dashboard rarely asks for one event by primary key. Instead, it scans a time range, groups rows by one or more dimensions, and calculates aggregates.
Because ClickHouse stores data by column, a report reads only the fields it needs. That’s a strong fit for analytics.
Plausible keeps two main native tables:
events_v2for pageviews, custom events, engagement, and propertiessessions_v2for visits, visitors, duration, bounces, and acquisition data
The event table is ordered for site-and-time queries
The events_v2 table is split into monthly partitions. Its ordering starts with:
site_id, date, event_name, user_id, timestamp
Most reports know the site and date range. Putting those values first helps ClickHouse skip unrelated data.
Events repeat session information on purpose
Before buffering an event, Plausible merges session information right into it. An event carries its session ID along with source, location, browser, device, and other values that also live on the session.
That duplicates data on purpose to avoid joins in many common reports. A report of pageviews by country can scan event columns directly instead of joining every pageview to the session table first. Storing a little more data makes those queries faster.
Postgres runs the product
Postgres holds the relational side of Plausible: accounts, teams, permissions, sites, goals, API keys, shared dashboards, email reports, and settings.
It also powers Oban, the background job system that rotates salts, sends reports, cleans old data, and runs imports.
Postgres handles the data that needs transactions, constraints, and relationships, while ClickHouse handles scanning large collections of measurements. You can see that boundary directly in the code:
Plausible.Repo -> Postgres product data
Plausible.IngestRepo -> ClickHouse writes
Plausible.ClickhouseRepo -> ClickHouse reads
Two databases mean more work
The split is the right choice for Plausible, though it does add operational work.
Deleting a site, importing data, or resetting analytics can affect both stores, and a single transaction can’t span both databases. You also have to back up and maintain both sides separately: a Postgres backup holds the product and its settings, and a ClickHouse backup holds the analytics data.
If you want to understand the database roles first, start with my database guide and introduction to PostgreSQL, then read the official ClickHouse architecture overview.
How the dashboard gets its reports
When you open a dashboard, Phoenix checks access and renders the page shell. React then sends report requests to:
POST /api/stats/:domain/query
Each request describes business concepts rather than SQL:
- metrics
- dimensions
- date range
- filters
- ordering
- pagination
- comparisons
- optional imported data
The server then turns that request into a ClickHouse query:
JSON report request
│
▼
Dashboard.QueryParser
│ validate metrics, dimensions, filters, and access
▼
Stats.QueryBuilder
│ construct the internal query model
▼
QueryOptimizer + TableDecider
│ choose events, sessions, or both
▼
SQL.QueryBuilder
│ construct Ecto/ClickHouse query
▼
ClickHouse
│
▼
QueryRunner
│ comparisons, labels, totals, formatting
▼
JSON response
I like this boundary: the browser asks for a report, and the server decides which tables and queries will answer it.
Choosing the events table, sessions table, or both
The TableDecider decides which table can answer a report.
Event metrics include:
- pageviews
- events
- scroll depth
- time on page
Session metrics include:
- bounce rate
- visit duration
- views per visit
- exit rate
Some metrics can come from either table, and dimensions matter too: a normal page belongs to an event, while entry and exit pages belong to a session.
Invalid questions are rejected early
Some combinations don’t have a clean meaning or would require unsupported joins, so TableDecider rejects them upfront. That’s the right call: an analytics API shouldn’t return a believable number for a question it can’t answer accurately.
Joins are conditional
The SQL builder starts with either events or sessions and only adds a join when a report needs both. For example, pageviews grouped by entry page pull data from both tables, so that’s when the builder joins events and sessions.
Most dashboard cards avoid joins because Plausible copies useful session data onto events when it receives them.
Comparisons run as a second query and get merged into the result. The real-time visitor number is simpler: Plausible counts recent temporary visitor IDs.
Imported analytics data is different
Plausible can import data from Google Analytics and CSV files. Because imported reports aren’t the same as native events, they use separate ClickHouse tables.
When a report supports imported data and overlaps an imported date range, the query builder merges the imported aggregate query with the native Plausible query. For reports that can’t mix imported and native data, the API returns a warning instead of inventing detail the imported source doesn’t have.
React owns one island, not the whole product
The StatsController draws a clear boundary: the dashboard is client-rendered, while the rest of the app isn’t built as one large client-side application.
Phoenix renders a page with the site’s initial settings, and the dashboard.tsx entry point reads those settings and mounts React into the page.
React Router keeps filters and date ranges in the URL so reports can be shared and the back button works. TanStack Query caches report results, refreshes real-time data, and cancels old requests when you change filters quickly.
Why React earns its place here
The dashboard has linked filters, multiple reports, charts, comparisons, real-time invalidation, pagination, search, and shareable URL state. React fits that work well, while the password reset page doesn’t need any of that machinery.
Everywhere else, Plausible uses Phoenix templates, LiveView, and Alpine.js. I like this choice: use a browser framework on the page where it helps, instead of making the whole product a client-side application because one screen needs it.
If you want to dig into that part of the code, my React guide covers components, state, effects, context, and routing.
The monolith is a supervision tree
Plausible deploys as one application, with many small Elixir processes running inside it.
The Application supervisor starts a long list of children, including:
- both database connections
- the session workers and caches
- event and session buffers
- background jobs
- the Phoenix web server
If one process crashes, the supervisor restarts it without taking down the rest of the app. You still deploy a single monolith, while Elixir handles concurrency and fault isolation inside it.
Observability follows the boundaries
Plausible measures how long each event step takes and counts why events get dropped. That way you can tell the difference between bot filtering, invalid data, site rules, and session problems.
What self-hosting actually runs
The official Community Edition repository comes with a Docker Compose setup running three main services:
The Compose file pins the application image, waits until both databases are healthy, runs migrations, and starts Plausible. Named Docker volumes keep your data across restarts.
The ClickHouse configuration is tuned to make a single-host Community Edition install practical, though ClickHouse still has real hardware requirements. You’ll want at least 2 GB of memory and a CPU with SSE 4.2 or NEON support.
If you’re new to containers, start with my Docker introduction and Introduction to Docker Compose. The Compose file gets much easier to read once services, networks, health checks, and volumes click.
A three-container setup is simple, not trivial
You can run all three services on one machine, and Docker Compose makes the setup reproducible. You’re still on the hook for backups of both databases, enough memory and disk space, working email delivery, HTTPS, and safe upgrades.
Where can data be lost or become approximate?
Plausible trades exact accounting for availability, speed, and privacy in several places.
On the client side, a browser can close before sending an event, a content blocker can stop it, or a network request can fail. Visitor counts are also estimates, because the temporary ID can occasionally join two people into one visitor or split one person into two.
On the server side, session state and write batches sit briefly in memory, so a sudden machine failure can drop a small slice of recent data. Configuration caches can also stay slightly out of date for a short time.
That’s a deliberate trade-off for web analytics. Losing a few pageviews barely shifts a report, whereas making every event fully durable before replying would slow the system down and make it harder to run. Whether you’d make the same trade-off comes down to what losing a small amount of data means for your product.
Why this architecture works
Each part of the stack handles a clear slice of the work:
tracker observes browser behavior cheaply
Phoenix validates, filters, enriches, and authorizes
ETS/GenServer coordinates short-lived session state
buffers convert individual events into batch writes
ClickHouse stores and aggregates measurements
Postgres protects relational product state
stats layer translates product metrics into database queries
React coordinates the interactive report interface
What makes this hold up over time is that the boundaries match the parts of the product that change independently. Attribution rules can change on the server without replacing the tracker. The session implementation can change without rewriting the controller or the earlier enrichment steps. And the dashboard can change its UI without ever giving the browser SQL access.
Even with all of that, the complete application still fits into one Phoenix release and two databases.
What I would copy
A few of Plausible’s design choices transfer well to smaller products:
- Keep the request path easy to follow. A small controller feeding an ordered pipeline is quick to read and debug.
- Put privacy in the data model. The temporary visitor ID expires by design, and raw IP addresses are never stored with events.
- Batch only the work that needs batching. Grouping pageviews cuts down database writes without complicating the rest of the app.
- Keep storage details behind the report API. React asks for metrics like visitors and bounce rate, without needing to know which ClickHouse table answered the query.
- Use React only where it earns its place. A dashboard with filters and charts needs rich client-side state, while a password reset page is fine server-rendered.
- Keep related work behind one boundary. The controller saves an event without knowing every detail of session state and buffering.
The deeper lesson: simple products can have sophisticated internals
From the outside, Plausible looks like one calm dashboard. Underneath, it coordinates browser code, request validation, privacy rules, session tracking, two databases, and an interactive reporting UI.
The product stays understandable because each layer has a clear job: the browser sends a small event, Phoenix processes it, ClickHouse stores the analytics data, and React receives finished report results rather than raw database rows.
That’s what I want to explore in this series: why real products divide their systems the way they do, and what each boundary makes easier.
I later used Plausible’s API as the foundation for a small Plausible Automation Toolkit.
What I’d do differently if I had to build this from scratch myself
Plausible’s current architecture reflects years of traffic, features, imports, and old tracker versions it still has to support. A new product doesn’t have any of that baggage, so I’d start with the smallest version that works.
One app and one database
Start with Phoenix and Postgres. Put everything in one append-only events table with the site, event name, time, page, source, country, device, and temporary visitor ID, and calculate sessions directly from those rows with a 30-minute gap starting a new session.
It won’t be as fast as Plausible, and that’s fine early on. A single database is far easier to build, back up, change, and understand. Bring in ClickHouse only when Postgres reports become a real problem.
One small tracker
Ship one tracker that records pageviews and custom events. File downloads, form tracking, outbound links, and the other variants can wait. Plausible’s tracker compiler makes sense today, but you don’t need it on day one.
Keep privacy from the start
Keep the rotating visitor ID right away. Let the server use the IP address to create that temporary ID, then discard it so the raw IP is never stored with the event. Privacy is much easier to design at the start than to add later.
Keep the event path readable
Keep the same pipeline order from the beginning:
parse
validate
filter
enrich
identify
save
At first, those can just be six small functions in one module writing events straight to Postgres. Once individual writes get too slow, add a small batch buffer.
The same rule holds for the rest of the system: add pieces only when you hit the bottleneck. Put an active-session cache in front of slow session queries, add ClickHouse when reports slow down in Postgres, extract a query builder once report endpoints get repetitive, and compile separate tracker variants only when tracker features pile up.
Use React only for the dashboard
This boundary is worth copying straight from Plausible. The dashboard has charts, filters, date ranges, and live updates, so React makes sense there. Login forms and account settings can stay server-rendered.
My first version
Put together, the v1 setup looks like this:
small JavaScript tracker
│
▼
Phoenix event endpoint
│
├── check the event
├── add location and browser data
└── create a temporary visitor ID
│
▼
Postgres
│
▼
a few fixed reports
│
▼
React dashboard
One app, one database, one tracker, and a few reports. From there, watch where real traffic makes things slow or awkward, and pull in Plausible’s heavier pieces only when you need them.
Want me to talk about your product? You can sponsor this site.
Related posts about database: