Software Engineering • Nov 25, 2024 • 14 min read

Audit Trails in Phoenix: Introducing Carbonite at Edge Payment Technologies

Z

Ziyan Junaideen

Lead Software Engineer (Ruby on Rails & Elixir Phoenix)

A red ruby tangled in cables wired straight into a database and to email, settings and notification icons, beside a tidy violet neon pipeline where data cards pass through a funnel with a check mark and a single gateway before reaching a database

Last week we added an audit trail to the merchant account at Edge Payment Technologies. Every insert, update and delete on a merchant now leaves a record of what changed, what it was before, who did it and when, and our admins can read that history on the merchant's page.

We did it with Carbonite, an Elixir library that captures changes with PostgreSQL triggers rather than in application code. This post covers why we wanted it, why we chose Carbonite over Elixir's PaperTrail and over what we used in Rails, what it costs, and the one mistake I keep making with it.

What Edge is

Edge is a payment gateway for high-risk merchants in the United States. Merchants apply, go through underwriting (identity checks on their officers and owners, business verification, bank and processing statements), and once approved they take card payments through our hosted checkout, payment links, invoices and a JSON:API that their own software connects to. Money settles to the bank accounts they set up as payout methods.

Edge started as a Ruby on Rails application. In 2023 we rebuilt it in Elixir and Phoenix, and today one Phoenix application serves the merchant dashboard, the staff admin section, hosted checkout and the API. Most of the screens are LiveView, and the data lives in PostgreSQL behind Ecto.

The merchant record is the centre of all of it. It holds the business's legal details, its tax ID, its addresses, its industry and merchant category code, its onboarding and underwriting state, and the settings that decide how it is allowed to process. Merchants edit parts of it during onboarding and in their settings, our underwriting and support staff edit other parts in the admin section, and background jobs and partner integrations change it too. If one record in the system deserves a history, it is this one.

Why audit trails matter

An audit trail answers questions that otherwise become arguments.

  • "Who changed this?" A merchant's business address or tax ID changed after approval. Was it the merchant, a member of our staff, or a job? Without a trail, the honest answer is "we don't know".
  • "What did it say before?" Underwriting decisions are made on the data in front of the analyst at the time. If that data later changes, we need to be able to show what it was when we approved the account.
  • Fraud. In high-risk payments, a common pattern is an account that looks clean at onboarding and then quietly changes: a new business description, a different website, a different phone number. A history of changes makes that pattern visible.
  • Support and debugging. "It was fine yesterday" is far easier to investigate when you can see exactly which fields moved, and in which request.
  • Accountability for staff. Our admins have a lot of power over merchant accounts. A trail protects the merchant from mistakes and protects the staff member who did the right thing.

The legal and compliance side

For a payment company the trail is not just nice to have. I'm an engineer, not a lawyer, so take this as the context we work in rather than legal advice.

  • PCI DSS. Requirement 10 of PCI DSS v4.0 is "Log and Monitor All Access to System Components and Cardholder Data". It expects audit logs that link actions to individual users and record the type of event, the time, whether it succeeded, where it came from and what it affected (10.2.2), and it expects that history to be kept for at least twelve months, with the most recent three months immediately available (10.5.1). PCI is mostly about cardholder data and system access, but a record of who changed a merchant's account is exactly the kind of evidence an assessor asks to see.
  • Sponsor banks and card networks. A gateway like Edge operates under agreements with its sponsor bank and the card networks. Those agreements oblige us to underwrite merchants properly and to keep records that prove we did. When the bank audits our merchant portfolio, "here is the application, here is every change since, and here is who made it" is the answer they want.
  • Anti-money laundering. US Bank Secrecy Act record-keeping rules generally expect financial records to be kept for five years. A trail of changes to the business and ownership details we verified is part of showing that our know-your-customer and know-your-business checks still hold.
  • Disputes and litigation. When a merchant relationship ends badly, a reliable record of what was on the account, and when it changed, is the first thing lawyers ask for.

There is one tension worth naming here: privacy. An audit trail that stores old values is also a second copy of personal data. When we scrub a merchant's details at the end of the relationship, the history still holds what was there before. Which data you keep, for how long, and how you remove it from the trail when you must are questions to settle with your compliance team before you switch auditing on, not after.

Where we came from: paper_trail in Rails

In Rails we used the paper_trail gem, the most popular auditing gem in that world. We added it in April 2023: has_paper_trail on the merchant account, users, charges, disputes, payment links, payout methods and about twenty other models, and a before_action :set_paper_trail_whodunnit in the application controller so every change recorded the signed-in user. Every change then wrote a row to a versions table. A month later we moved the stored objects from YAML to JSON columns, which made them queryable and saved us from YAML's safe-loading headaches.

paper_trail served us well. Its weakness is the one every callback-based tool shares: it only sees changes that go through ActiveRecord callbacks. update_column, update_all, insert_all, delete_all, a data fix in a migration, or a query in psql all bypass it silently.

If you are on Rails and weighing the options, the main ones are:

  • paper_trail: model callbacks, one shared versions table, whodunnit for the actor, and a rich API for reifying old versions. The default choice.
  • audited: also callback-based, with an audits table, associated audits and comments on changes. Similar trade-offs to paper_trail.
  • Logidze: PostgreSQL triggers that store each record's history in a jsonb column on the row itself. Because it works in the database it catches update_all and raw SQL too, and it is the closest thing in Rails to what Carbonite does.

When we moved to Phoenix, the audit trail did not come with us at first. The new Ecto schemas were written from scratch and auditing was on the list of things to come back to. Last week we came back to it.

The Elixir options

There are three libraries worth looking at in Elixir.

PaperTrail (the Elixir one) is inspired by the gem. Instead of Repo.insert and Repo.update you call PaperTrail.insert and PaperTrail.update, which write your change and a versions row in one transaction, with an originator for the actor. It is easy to understand, and it works on any database Ecto supports.

ExAudit wraps your Repo so that its normal functions track changes for the schemas you configure, again at the application level.

Carbonite, from bitcrowd, takes the Logidze route: triggers in PostgreSQL record every change, and the application only has to say which transaction it is in.

Here is how PaperTrail and Carbonite compare on the things that mattered to us:

PaperTrail (Elixir) Carbonite
Where changes are captured In Elixir, when you call PaperTrail.insert/update/delete In PostgreSQL, by a trigger on each table
Repo.update_all, raw SQL, data migrations, psql Not recorded Recorded
Forgetting to use it The change is saved without a version, silently The write fails with an error
Who and why originator and meta on each version meta on the transaction, shared by every change in it
Grouping One version per record change One transaction row, many change rows
Databases Any Ecto adapter PostgreSQL only
Previous values Stored in the version Optional, with store_changed_from

The deciding row for us was the third one. With an application-level tool, a forgotten call means a gap in the trail that nobody notices until an auditor or a lawyer asks for that exact change. With Carbonite, a forgotten call means an error in development or in a test. For records that a bank may one day ask about, I would rather the system refuse the write than quietly skip the history.

We are on PostgreSQL and have no plans to leave it, so being tied to it costs us nothing.

How Carbonite works

Carbonite's migrations create a carbonite_default schema with a few tables:

  • transactions: one row per database transaction that changed an audited table, with a meta JSON column for whatever context you attach and a timestamp.
  • changes: one row per changed record, with the operation (insert, update or delete), the table, the primary key, the record's data, the list of fields that changed, and optionally their previous values.
  • triggers: the configuration for each audited table.

A trigger on each audited table writes the changes row. It links that row to the current database transaction, so it expects a transactions row to have been inserted earlier in the same transaction. If there isn't one, the trigger raises and the whole transaction rolls back. That is the safety net I described above, and also the source of most of the friction.

Our setup

The migration

We audit one table for now, merchants:

defmodule Dashboard.Repo.Migrations.InstallCarbonite do
  use Ecto.Migration

  def up do
    Carbonite.Migrations.up(1..11)

    Carbonite.Migrations.create_trigger("merchants")
    Carbonite.Migrations.put_trigger_config("merchants", :store_changed_from, true)
    Carbonite.Migrations.put_trigger_config("merchants", :excluded_columns, ["updated_at"])
  end

  def down do
    Carbonite.Migrations.drop_trigger("merchants")
    Carbonite.Migrations.down(11..1//-1)
  end
end

Two options matter:

  • store_changed_from records the old value of every changed field, not just the new state. Without it you can rebuild the history by comparing consecutive changes, but with it each change answers "from what, to what" on its own, which is what our admins want to read.
  • excluded_columns: ["updated_at"] leaves the timestamp out of the captured data. It changes on every write, so it adds noise to every diff and tells us nothing the transaction's own timestamp does not.

Recording who did it

Carbonite lets you put metadata into the process dictionary at the edge of the system, and picks it up when the transaction row is inserted. We do that where we already know who the user is: in the plug that loads the current account, and in the LiveView on_mount hook that does the same for sockets.

def fetch_current_account(conn, _opts) do
  {account_token, conn} = ensure_account_token(conn)
  account = account_token && Dashboard.Users.get_account_by_session_token(account_token)

  if account do
    Carbonite.Transaction.put_meta(:account_id, account.id)
  end

  assign(conn, :current_account, account)
end

Both places matter. A LiveView runs in its own process, separate from the HTTP request that first rendered it, so metadata stored by the plug is not there when a handle_event saves a form.

Writing changes

Every write to a merchant now starts by inserting a Carbonite transaction. With Ecto.Multi, it is one extra line:

Ecto.Multi.new()
|> Carbonite.Multi.insert_transaction()
|> Ecto.Multi.update(:merchant, Merchant.merchant_settings_changeset(merchant, attrs))
|> Dashboard.Repo.transaction()

Outside a Multi, it goes first inside the transaction:

Dashboard.Repo.transaction(fn ->
  with {:ok, _transaction} <- Carbonite.insert_transaction(Dashboard.Repo, %{meta: %{}}),
       {:ok, merchant} <- Dashboard.Repo.update(changeset) do
    merchant
  else
    {:error, reason} -> Dashboard.Repo.rollback(reason)
  end
end)

Background jobs and integrations have no signed-in user, so they put their own context in meta, such as the job that ran, to make it clear the change did not come from a person.

Reading the history

Carbonite ships query helpers, so the admin view of a merchant's history is short:

merchant
|> Carbonite.Query.changes(order_by: {:desc, :id})
|> Dashboard.Repo.all()
|> Dashboard.Repo.preload(:transaction)

The page lists each change with its operation, every changed field as before -> after, the transaction's metadata and how long ago it happened.

The performance overhead

Triggers are not free, but for this table the cost is small.

  • One extra insert per transaction, into transactions, and one extra insert per changed row, into changes, both in the same database transaction as the write.
  • The trigger serialises the row to JSON and, with store_changed_from, compares old and new values to work out what changed. That is a little CPU on the database for every write to an audited table.
  • Storage grows forever unless you plan for it. Each change stores a full copy of the row plus the old values of the changed fields. A wide table with large text or JSON columns makes for large change rows.
  • Writes take slightly longer to commit, and the extra rows add to WAL volume and replication traffic.

What makes it a non-issue for us is the write pattern. A merchant is written a handful of times during onboarding, then occasionally in settings, by underwriting and by integrations. That is a tiny fraction of our database traffic, and the extra inserts cost microseconds per write. I would think much harder before putting a trigger on a table that takes thousands of writes a second, such as payment events, where the history is better kept as append-only rows in its own right.

Two more things to keep in mind:

  • Excluding noisy columns keeps the change rows smaller and the diffs readable. updated_at was the obvious one for us.
  • Retention is up to you. Carbonite has an outbox mechanism that lets you process changes in order, for example to ship them to long-term storage and then purge them. We keep everything in the database for now; with our volume that will not be a concern for a long time.

The complications

I keep forgetting the transaction

This is the honest part. More than once, I have written a new function that updates a merchant, run it, and been met with:

UPDATE on table public.merchants without prior INSERT into carbonite_default.transactions

It is the system working as designed, and it is annoying every time. It is especially easy to forget in code that does not look like it is about merchants: a job that runs after onboarding, a webhook from a partner, an onboarding step that updates a field as a side effect. Every one of those writes needs the transaction, and the error only appears when that code path runs.

That makes tests the real safety net. If a code path is tested, the error surfaces in the test run. If it isn't, it surfaces in production, as a failed request or a failed job. Better than a silent gap, but not by enough to be comfortable.

What helps:

  • Search for writes. Before merging, grep for Repo.update, Repo.insert and Repo.delete on audited schemas and check each one is inside a Carbonite transaction.
  • Wrap the pattern. A small helper such as audited_transaction(fun) that always inserts the Carbonite transaction first leaves one thing to remember instead of two.
  • Make it a custom Credo check, eventually, so the reminder comes from the linter and not from Postgres.

Tests and fixtures

Every fixture that creates or updates a merchant now needs a Carbonite transaction too. For tests where the history is irrelevant we switch the triggers off for the current database transaction:

def with_ignored_carbonite(repo, fun) do
  Carbonite.override_mode(repo, to: :ignore)
  result = fun.()
  Carbonite.override_mode(repo, to: :capture)
  result
end

override_mode uses SET LOCAL, so it only affects the current database transaction. With the Ecto SQL sandbox, each test runs in its own transaction, so the override cannot leak into other tests.

Metadata belongs to a process

Because put_meta writes to the process dictionary, the metadata only exists in the process that set it. The HTTP request, the LiveView process and each Oban job are separate processes, and each needs its own. A Task started to save something in the background starts with nothing. When the account_id is missing from a change, this is almost always why.

Recording the "why"

Carbonite records who, what and when very well. It does not know why. "Support updated the address after a phone call with the owner" or "underwriting corrected the MCC after review" is the context an auditor really wants. Carbonite gives us somewhere to put it, the transaction's meta, but we still have to collect it from the person making the change. We haven't solved that in the UI yet.

Console sessions

A change made from a remote iex session on production needs a Carbonite transaction like any other, and it should carry metadata saying who was at the console. The trigger makes sure nobody can skip the first part by accident. The second part is a team habit we still need to write down.

What's next

For now Carbonite covers the merchant account only. That was deliberate: it is the most important record, it let us prove the approach, and it showed us where the friction is before we spread it across the codebase.

The plan is to extend it to other schemas, starting with the ones a bank or an auditor is most likely to ask about: payout methods, where a changed bank account is one of the clearest fraud signals there is, the officers and beneficial owners behind each merchant, and the processor and fee settings that decide how a merchant is allowed to transact. Each new table is a three-line migration. The real work is going through every code path that writes to it and making sure each one starts with a Carbonite transaction, which is why I'd like the helper and the Credo check in place first.

If you are adding an audit trail to a Phoenix application on PostgreSQL, I recommend Carbonite. It costs a little discipline on every write, and in exchange you never have to wonder whether the history is complete.

Discussion

0

You need to be logged in to post a comment.

Log in to Comment

No comments yet. Be the first to join the conversation.