$ emrebener
home personal-projects opal samples

Opal Samples

technologies: .net, c#, postgresql, ef core, quartz.net, redis, mediatr, stripe, react, typescript, electron, opentelemetry, docker repository: closed source
published: updated: type: build

Opal Samples is a marketplace for music sample packs that are made collaboratively. Artists submit individual sounds into a project, a reviewer on the label side accepts the ones that fit, and an admin promotes a finished project into a product. Buyers pay through Stripe, and every contributor to the project earns a calculated share of each sale. It isn’t live yet.

The system behind it is a .NET 10 modular monolith of eleven modules: about 61,000 lines of C# with about 68,000 lines of tests, a React 19 frontend of about 54,000 lines, and an Electron desktop tool for the artists. The part of its history worth the most space is from July 2026, when I removed the message bus the whole design had been built around.

1. The product and the system

The backend splits into eleven domain modules: Identity, Roster, Projects, Catalog, Commerce, Payouts, Media, Notifications, Admin, Audit and Feedback. Each module that stores data owns one PostgreSQL schema. There are no foreign keys between schemas, and every cross-module reference is a bare Guid, a choice that pays off again in account erasure (section 6).

A host project owns what doesn’t belong to one module: middleware, authentication, the scheduled jobs, and the orchestrators that write across several schemas at once, such as order completion and project promotion.

Every command and query is a small record dispatched through MediatR to one handler, and both return a Result<T>. An expected failure, such as adding an archived product to a cart or requesting a payout below the minimum, is a result with a stable error code, never an exception. Three pipeline behaviors wrap every handler: logging, validation, and a pagination bound that rejects out-of-range page requests instead of silently clamping them.

Around the application sit PostgreSQL, Redis as a cache, Quartz.NET with a clustered Postgres store for background work, Stripe for checkout and payouts, S3-compatible object storage, and a CDN in front of it.

2. Removing the message bus

The original goal was strictly independent modules that communicate only through integration events over MassTransit and RabbitMQ, so that a later split into microservices would be easy. I ruled microservices out for good, because the traffic will never need them, and then asked whether the bus still earned its place. Four code investigations ran in parallel: an event catalog, a coupling audit, a caching audit, and the bus’s operational footprint.

2.1. What the review found

  • The bus’s reliability was illusory. There was no durable outbox. Every publisher committed its database transaction first and then published from an in-memory buffer, so a crash or a deploy in that window silently lost the event. Delivery was at-most-once in practice. Making events reliable would have meant adding infrastructure, while making synchronous calls reliable only meant doing the work inside the transaction the code already had.
  • The system already distrusted it. The state that mattered lived in Postgres tables built because queue state couldn’t be trusted, and reconciliation jobs swept up what the event flows missed.
  • The money paths had already left. Order completion, refunds, chargebacks and payouts were synchronous transaction scripts committing across modules in one transaction, with the financial audit log written inline.
  • Most of what it carried was trivial. Of about 40 event types, 12 were dead: no publisher, no consumer, or neither. The live ones mostly did a cache remove, wrote an audit row, or translated into an email. Two were real cross-module workflows, and three were work that really needed to run in the background.
  • Failures went nowhere. Of about 29 consumers, 2 had fault handling. Everything else that exhausted its retries landed in error queues that nothing consumed and nobody watched.
  • The module boundaries were already fiction. 57 files injected another module’s DbContext, across 18 directed boundaries. Nearly all of those were reads.
  • The cache invalidation registry was ceremony. It protected 15 keys and had 7 bugs. The root cause was three hops of indirection (mutation, to the right event, to the right registry rule, to the right key) where one greppable inline call would do.

2.2. Three options

The purist option was to restore the original design: module facades everywhere, a transactional outbox and inbox, and the 57 cross-context call sites eliminated. That was weeks of work whose only payoff was an easier split into services that will never happen. Eventual consistency between modules in one process sharing one database solves a distributed-systems problem this system doesn’t have.

The opposite option, making everything synchronous, would have put minutes of FFmpeg and flaky email-provider calls inside HTTP requests.

I went with the option between them. Side effects that take milliseconds became synchronous in-process calls. The three workloads that need background execution (the asset pipeline, waveform generation and email) were rebuilt on the Postgres and Quartz infrastructure the application already ran. MassTransit and RabbitMQ were deleted.

2.3. Five stages

StageWhat it did
1. Pure deletionsThe 12 dead events and the cache keys that were invalidated but never written
2. Inline the millisecond consumersSeven narrow module contracts replaced every cache, audit, notification, cleanup and workflow consumer
3. Email over PostgresThe email log table became a transactional outbox with a Quartz dispatcher
4. Pipeline and waveforms on QuartzThe last consumers and the invalidation registry were deleted, leaving the bus idle
5. TeardownPackages, broker, config, health check and test harness removed

The migration ran from 3 to 5 July 2026, with a gate of a clean build and the full test suite between stages. At the end, removing the packages left the build green, which showed that no source reference had survived.

The contracts that replaced the events are small synchronous interfaces, implemented by the module that owns the data and resolved at runtime. This is the one for email:

/// <summary>
/// Transactional email outbox. Implemented by the Notifications module.
/// EnqueueAsync inserts a Queued email_logs row with a plain SaveChangesAsync, so when the caller
/// has an ambient TransactionScope the email commits atomically with the caller's writes
/// (the ICartMaintenanceService precedent); otherwise it commits immediately.
/// A Quartz dispatcher renders and sends queued rows within ~15 seconds.
/// </summary>
public interface IEmailQueue
{
    Task EnqueueAsync(
        string templateKey,
        string toEmail,
        Dictionary<string, string>? variables = null,
        bool isCritical = false,
        Guid? correlationId = null,
        CancellationToken cancellationToken = default);
}

The rule that came out of the coupling audit is deliberately modest. Cross-module reads through an injected DbContext are legitimate. Cross-module writes go through the owning module’s contract or through a host orchestrator under a transaction.

3. What stays asynchronous

Three workloads run in the background, and each one keeps its queue state in Postgres.

3.1. The asset pipeline

When an admin promotes a project, a durable Quartz job turns a folder of accepted submissions into a downloadable product. It runs nine phases in order: load the data, download the WAVs to a temp directory (a pack is 300 to 500 MB, too much to hold in memory), process the audio at 24-bit and 16-bit, generate previews, generate the demo, build the ZIPs, upload them with a SHA-256 hash, save the records, and finalize with one deduplicated CDN purge and a cache remove.

Per-step status is stored as JSON on the trigger row, keyed by the names of an enum’s members, so the enum carries a warning never to rename them. The admin panel polls that row every two seconds and shows which step a run is on or failed at.

Three choices here look like omissions and aren’t:

  • Failures aren’t retried. A failed run records its step and error on the trigger and stops, and the admin re-promotes with one click. Promotion is a rare, interactive operation guarded to one at a time globally, so silent resurrection would buy nothing.
  • The project is never reverted on failure. A half-promoted product is the state the admin needs to see to diagnose it.
  • A reaper marks stuck runs failed and doesn’t re-run them. Every five minutes a job fails any trigger that was never picked up within five minutes, or that has been running for more than 35. That’s how a run killed by a deploy gets noticed, which the bus had no way to do, and it keeps the one-at-a-time guard from wedging.

Quartz won’t kill a hung job, so the 30-minute timeout is enforced inside the job. Every FFmpeg invocation goes through one runner with its own timeout, a kill of the entire process tree, arguments passed as a list instead of a command string, and capped output capture. The kill matters: waiting for exit alone never terminates the child, and before the runner existed a timed-out pipeline left FFmpeg running orphaned.

3.2. Waveforms and email

Waveform generation runs on an in-process channel drained by a hosted worker. It’s fire-and-forget, so a reconciliation job every five minutes re-enqueues any audio file still missing its waveform. The guarantee comes from the sweep, not the queue.

Email is the transactional outbox from the interface above. A producer inserts a row inside its own transaction, so an order-confirmation email commits or rolls back with the order. A dispatcher picks up due rows every 15 seconds and retries on a ladder of 5 seconds, 30 seconds and 2 minutes. A permanent failure writes an audit row, and for a critical email it alerts every administrator in the app. Under the bus, emails were published after the commit and could be lost. Now they can’t be sent for a transaction that rolled back, or lost for one that committed.

4. Money

Earnings are computed when an order completes, not by a monthly batch. When Stripe reports a completed checkout, an orchestrator runs a revenue waterfall over every line item:

OrderItem.ChargedAmountMinor
  -> minus the platform fee
  -> roster pool (the remainder)
  -> split into a submission pool and a management pool
  -> submission pool divided across contributors, weighted by content type
  -> management pool paid per reviewed submission to its reviewer;
     the share of unreviewed submissions rolls into the submission pool

The calculation is a pure service with no database access. It emits one ledger row per order item, artist, pool and type, and each row carries a snapshot of every percentage and weight that produced it. Recomputing from the snapshot months later, after the settings have changed, still gives the original number.

All money is a long of GBP pence. Each stage of the waterfall floors to a penny and hands the remainder to the top recipients, so the shares always sum to the pool exactly:

// Calculate floor shares
var shares = recipientPoints
    .Select(kvp => new
    {
        kvp.Key,
        Points = kvp.Value,
        Share = (long)Math.Floor(poolAmount * kvp.Value / totalPoints)
    })
    .OrderByDescending(x => x.Points)
    .ToList();

var sumOfShares = shares.Sum(x => x.Share);
var remainder = poolAmount - sumOfShares;

// Distribute remainder pennies to top recipients by points
var result = new Dictionary<Guid, long>();
for (var i = 0; i < shares.Count; i++)
{
    var extra = i < remainder ? 1L : 0L;
    result[shares[i].Key] = shares[i].Share + extra;
}

Discount proration follows the same rule at the order layer, with the invariant that the items’ charged amounts sum to the order total to the penny. Earnings can’t drift from order totals, because the rounding choice is made once and carried forward as data.

4.1. One transaction across modules

Order completion marks the order paid, creates the download rows and the earnings rows, writes the financial audit log and enqueues the confirmation email, all in one transaction that spans several modules’ contexts. Every such scope comes from one factory:

public static TransactionScope Create() => new(
    TransactionScopeOption.Required,
    new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadCommitted,
        Timeout = TransactionManager.DefaultTimeout
    },
    TransactionScopeAsyncFlowOption.Enabled);

The isolation level is pinned because Postgres maps the System.Transactions default to serializable, which surfaced serialization failures as 500s for no benefit here.

4.2. Order writes can’t overwrite each other

Order carries Postgres’s xmin as a row version, so a read-modify-write either sees its own read still current or throws a concurrency exception. The rule exists because of a money bug. The checkout handler read a pending order early, ran several round trips of validation, then cancelled it. A payment webhook committing inside that window was overwritten, which left a paid order, with downloads and earnings written, sitting at cancelled. Nothing detected it, because completion had succeeded and the reconciliation job only scans pending orders. The signature was an order with both a completed and a cancelled timestamp. Every order write path now handles the conflict, and at a webhook that means a 500 that Stripe retries.

4.3. Refunds, chargebacks and alarms

A refund or chargeback never mutates the original earnings. It creates compensating negative rows linked to the sale rows, and a partial unique index is the database backstop against reversing the same row twice. A dispute that’s later won re-credits the artists through positive adjustment rows. An artist’s balance is the sum of their open rows, with no second source of truth to keep consistent.

Some events should never happen: a partial refund, a refund with no matching order, a reversed transfer. Those are persisted as finance alarms, deduplicated on Stripe’s event ID, and emailed to every administrator. Both webhook signing secrets are validated at startup, because an empty secret would make the signature check accept anything and a forged completion event would mint downloads and earnings.

5. Payouts

There are two payout rails, derived fresh on every call from the artist’s payout country: Stripe Connect for the UK, the EEA and Switzerland, and an admin-serviced bank transfer everywhere else. There’s no rail flag to migrate, so extending the supported list moves artists across automatically.

A Stripe payout completes synchronously. A transfer from the platform to a connected account settles when the create call returns, and Stripe removed the transfer.paid and transfer.failed events in an API version from 2017, so there’s no webhook to wait for. A successful call is the confirmation. If the call throws, the handler compensates: the payout is marked failed, the reserved earnings are released, and the artist is emailed.

What prevents two active payouts for one artist is the database, through a filtered unique index:

// Prevent concurrent active payouts per artist
builder.HasIndex(x => x.ArtistId)
    .IsUnique()
    .HasDatabaseName("IX_payouts_artist_active")
    .HasFilter("\"Status\" IN (1, 2)"); // Requested, Processing

The payout handler also contains a SELECT ... FOR UPDATE that does nothing. It runs in autocommit, so Postgres drops the lock the moment the statement ends. The real guards are the index above and a row version on the earnings. A lock that silently does nothing is exactly what survives code review, so a test scans the source for every raw row lock and fails until each one is declared with its semantics:

private static readonly Dictionary<string, string> ClassifiedRowLockSites = new()
{
    ["Modules/Opal.Modules.Commerce/Application/Common/DiscountRedemption.cs"] =
        "HOLDS — runs inside the caller's ambient TransactionScope; reserves the discount redemption cap.",
    ["Modules/Opal.Modules.Payouts/Application/Commands/RequestPayout/RequestPayoutCommand.cs"] =
        "INERT — runs in autocommit; the real guards are the ArtistEarning xmin token and IX_payouts_artist_active.",
};

I left the inert lock in place on purpose. Wrapping it in a transaction would change payout concurrency for no established reason, and that needs its own analysis of the money invariants first.

A reconciliation job runs every six hours as the safety net. A payout stuck in the requested state for more than 48 hours means the process died between reserving the earnings and the Stripe call. The job searches Stripe’s transfers for the payout’s ID in their metadata. If a transfer exists, the payout is completed, and if not, it’s failed and the earnings released. A suspended artist is never paid, and that’s checked before any state changes.

6. Security and compliance

CSRF is stopped by a required header, not by the cookie. Every state-changing request must carry a custom header or it’s refused with a 403 before authentication runs. A cross-site form post is still sent with the session cookie whatever CORS says, and for a forced withdrawal the attacker doesn’t need to read the response. A custom header can’t be set by a form, and adding one makes the request non-simple, which forces a preflight that the origin allowlist denies. The exemptions are few, and each is authenticated by something other than the cookie:

private static readonly string[] ExemptPaths =
[
    // Stripe -> us, server-to-server, no cookie, already signature-verified against the raw
    // body. Blocking these would break payments outright.
    "/api/webhooks/stripe",
    "/api/webhooks/stripe-connect",

    // RFC 8058 one-click unsubscribe. The POST originates from Gmail's / Yahoo's own
    // infrastructure, which will never send a custom header, and bulk-sender rules require the
    // endpoint to work. Safe to exempt: it is authenticated by the HMAC unsubscribe token, so
    // anyone able to forge the request already holds a valid token and could just call it.
    "/api/newsletter/unsubscribe/one-click",

    // Liveness/readiness probes.
    "/health"
];

An exception’s HTTP status comes from its type, never from its message. Domain exceptions carry stable codes and map to 400, 404 or 409, a few framework types have their own arms (401, 504, 501), and anything untyped falls through to a 500 with a generic body. There’s deliberately no mapping for ArgumentException or InvalidOperationException, because the framework throws those constantly and the type says nothing about whose fault the request was.

Uploads are verified after the fact. One matrix defines the accepted formats per workflow, the declared MIME type and the file extension have to agree, and unknown pairs fail closed. A presigned upload URL binds the content type but no maximum length, so every completion path checks the stored object’s real size and discards it on a mismatch.

Logs carry no personal data. Logging records a request’s type name and never the request object, because commands are records whose ToString() renders every property, passwords and bank details included. No email address or username is logged either, since application logs ship to a third party.

Account erasure is built on the absence of foreign keys. Because every cross-module user reference is a bare Guid, erasing a person means destroying every direct identifier and leaving opaque IDs on the records the law requires keeping. The financial rows survive and keep reconciling, and they no longer resolve to anyone. The server decides between three classes: a hard delete, an anonymized tombstone when a completed order exists, and a payout-only erasure for someone with accepted material, a review they performed, or any earning, whose profile is stripped while they stay payable. A reviewer falls in the last class, because a review earns from every future sale, and hard-deleting them would compute money for a ghost. An unpaid balance blocks erasure outright until it’s settled. All the database work is one transaction over nine contexts.

Several of these rules are enforced by tests that scan the source instead of exercising behavior: every row lock classified, every paged query bounded, no swallowing writer called inside a transaction scope, no personal data in log calls, every nullable result returned the right way, no culture-dependent currency format string. A convention that lives only in a document gets broken by the next change, and a convention with a failing test attached doesn’t.

7. Frontend and asset delivery

The frontend is React 19 with TypeScript, Vite, Tailwind and shadcn/ui. Server state lives in React Query, and ephemeral client state lives in Zustand stores.

One HTMLAudioElement lives in a store and the whole app shares it, so pressing play on one track pauses whatever was playing elsewhere with no event bus and no second element to keep in sync. The waveform player is a canvas that paints 128 normalized peaks computed on the server, and it reads its colors from CSS custom properties on the canvas element itself, so a scoped theme override reaches it.

Asset URLs go through one level of indirection. A request for a product’s cover hits the backend, which checks access once and answers with a 302 redirect to a token-authenticated CDN URL. Application code never handles a raw CDN URL or a signing token. Versioning is in the storage key: covers carry a content hash, avatars a version, and replaced submission audio gets a new key, so the CDN can’t serve stale bytes for a changed asset. Download links for purchased packs are signed for 30 minutes by default and capped at two hours, because that lifetime is the whole access window for a leaked URL.

Public pages ship in the entry chunk, and the roster and admin areas each build into one lazy chunk, so customers never download code for screens they can’t reach.

Covers are generative. There’s no image upload: a cover is defined by renderer parameters stored as JSON, rendered in the browser, and captured as two JPEGs that the API stores, a 1024-pixel web image and a 3000-pixel master that the asset pipeline embeds in the pack’s ZIPs. The renderer’s finishes and typography systems are frozen by version, so a cover made today renders the same after the renderer moves on.

8. Operations and testing

The API and the web app ship as Docker images behind Traefik, which applies the security response headers in one place. The API image runs as a non-root user with FFmpeg on the path, and applies every module’s migrations at startup. Logs, metrics and traces go out over OpenTelemetry to Grafana Cloud. There’s deliberately no long-term log store, because the durable records (audit logs, the financial audit log, the email outbox, finance alarms, server-fault rows) live in Postgres. Scheduled logical backups go to object storage.

Eleven Quartz jobs run on a schedule, and most of them are safety nets for something that should already have happened: order reconciliation against Stripe’s session state, payout reconciliation, Stripe account status re-sync, the pipeline reaper, the waveform sweep, a readiness sweep, and a sweep that aborts abandoned multipart uploads the storage provider would otherwise keep billing for.

CI runs on every push and pull request to the main branch: a release build with warnings as errors, the unit tests, the integration tests against real services in containers, a frontend production build, and a typecheck, lint, test and smoke run for the desktop tool.

The backend has 2,639 test methods, 2,382 unit and 257 integration. The rule for which is which matters more than the count: EF Core’s in-memory provider silently ignores filtered unique indexes and doesn’t honor real transaction semantics, so money math, unique indexes, rollback atomicity, row versions and raw SQL are tested against real Postgres. The project’s rule is that every financial invariant carries a test that fails if it breaks.

The tests use hand-written fakes instead of a mocking library, one per module contract. Most are a few dozen lines with accessors for what was captured, so asserting that an order completion enqueued a confirmation email is one call.

9. Side tools

Layer Studio is an Electron desktop tool for roster artists, about 15,000 lines, that layers random one-shots into new sounds. It’s strictly online and reuses the web session cookie, so there’s no second auth scheme. Releases are CI artifacts described by a manifest that the API validates fail-closed: a malformed manifest is a logged 500 by design, because a broken release artifact should be loud and not an empty download page.

The name generator produces names for sounds and packs from 427 categories in 13 groups, most of them declarative data. Its registry is explicit, one import per category, because the earlier glob-based version tied the library to the bundler and let a category’s ID drift from its filename unnoticed. Generation draws only from an injected random source, and a test runs every category twice under one seed to keep it reproducible.