I recently finished a project I can't name, but I can write about how it is built. And it is built boringly - which is a compliment.

In short: architecture studios publish their house designs (floor plans, rooms, photos, prices) and their customers browse the offer on the studio's page. There is a studio admin panel, a panel for the operator of the whole platform, subscriptions, a contact form, data export. Many companies in one database.

The stack:

  • .NET 10, a single ASP.NET Core host,
  • Blazor - pages rendered on the server, no WebAssembly, no JS bundle,
  • Tailwind CSS 4 built by its CLI from MSBuild,
  • PostgreSQL 18 - and this is where the fun is, because the business logic lives in the database.
A studio admin's dashboard on the demo account: views from the last 30 days, published designs, drafts, photos and the most viewed designs

Rule number one: C# never writes to tables

Every write is a procedure, every read is a view or a RETURNS TABLE function. No EF Core, no Dapper with INSERTs, no repositories. The host opens a transaction, tells the database who is asking, and calls a procedure:

SQL
BEGIN;
SELECT set_config('app.actor_id', '0193…', true);   -- who is asking: from the session, this transaction only
CALL projects_app.project_set_status('0193…', 'published', 812345);
COMMIT;

Schemas are split per module and per "visibility":

SchemaWhat is in it
projectstables - nobody outside touches them
projects_appprocedures and views for the application - the module's "API"
projects_internalhelpers, called only by other procedures or background work
projects_publicviews for anonymous visitors of the site

A module reads only its own tables and the _app schemas of lower modules. You can see the bounded contexts in \dn.

What a procedure looks like

A real example (role names shortened): publishing a house design on the studio's page. Messages are in Polish, because they go to the user as they are.

SQL
CREATE OR REPLACE PROCEDURE projects_app.project_set_status(
    p_id uuid,
    p_status text,
    INOUT p_row_version bigint
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
DECLARE
    v_actor_id uuid := platform.require_actor_id();
    v_status text;
    v_current_row_version bigint;
BEGIN
    IF NOT platform.actor_has_role(ARRAY['admin']) THEN
        RAISE EXCEPTION 'Tylko administrator zarządza projektami.' USING ERRCODE = 'U1310';
    END IF;

    SELECT p.status, p.xmin::text::bigint INTO v_status, v_current_row_version
    FROM projects.projects AS p
    WHERE p.id = p_id
    FOR UPDATE;
    IF NOT FOUND THEN
        RAISE EXCEPTION 'Nie ma takiego projektu.' USING ERRCODE = 'U1410';
    END IF;
    IF v_current_row_version IS DISTINCT FROM p_row_version THEN
        RAISE EXCEPTION 'Ktoś inny zmienił ten projekt. Odśwież stronę i spróbuj jeszcze raz.'
            USING ERRCODE = 'U1901';
    END IF;
    IF v_status = p_status THEN
        RETURN;                                   -- same status = no-op, nothing in the audit
    END IF;
    IF p_status = 'published' AND NOT EXISTS (
        SELECT 1 FROM projects.images AS i WHERE i.project_id = p_id AND i.is_cover
    ) THEN
        RAISE EXCEPTION 'Dodaj co najmniej jedno zdjęcie (okładkę), zanim opublikujesz projekt.'
            USING ERRCODE = 'U1031';
    END IF;

    UPDATE projects.projects AS p
    SET status = p_status,
        published_at = coalesce(p.published_at, CASE WHEN p_status = 'published' THEN now() END),
        modified_at = now(),
        modified_by = v_actor_id
    WHERE p.id = p_id;

    SELECT p.xmin::text::bigint INTO p_row_version FROM projects.projects AS p WHERE p.id = p_id;
END
$$;

A few things doing the work here:

  • SECURITY DEFINER + SET search_path - the procedure runs with the rights of the tables' owner, while the role the application connects as has only EXECUTE on projects_app. Without search_path someone could plant their own function in public - so always pg_catalog, pg_temp and fully qualified names.
  • xmin as the row version. Every change of a row in PostgreSQL gives it a new xmin, so optimistic concurrency comes for free - no version column, no trigger. The form keeps p_row_version, the procedure compares it, and on a mismatch raises U1901, which the host turns into a 409.
  • Own SQLSTATE codes. U1xxx are my codes, with a range per module (U13xx permissions, U14xx missing row, U19xx conflicts). The message is written for people, so the UI shows it as it is.
  • The business rule next to the data. "You don't publish without a cover" lives in one place. The panel, the tests, a migration script, a future mobile app - they all get the same answer.

Ids from the client, and a repeated request is a no-op

The page generates the ids of new aggregates, not the database:

C#
var id = Guid.CreateVersion7();   // .NET 9+: UUID v7, time-ordered, friendly to a B-tree

The creating procedure takes p_id and is idempotent: the same id with the same data returns the existing row, the same id with different data is a conflict.

SQL
SELECT p.id, p.slug, p.code, p.name INTO v_existing.id, v_existing.slug, v_existing.code, v_existing.name
FROM projects.projects AS p
WHERE p.id = p_id AND p.tenant_id = v_tenant_id;
IF FOUND THEN
    IF v_existing.slug = p_slug AND v_existing.code = v_code AND v_existing.name = btrim(p_name) THEN
        SELECT p.xmin::text::bigint INTO p_row_version FROM projects.projects AS p WHERE p.id = p_id;
        RETURN;                                    -- a retry of the same request
    END IF;
    RAISE EXCEPTION 'Ten identyfikator ma już inny projekt.' USING ERRCODE = 'U1910';
END IF;

A double click on "Save", a timeout halfway, a retry loop - none of it creates duplicates.

And the plan's limit ("before paying, a studio has one design") holds against two requests at once thanks to an advisory lock for the transaction:

SQL
IF identity.tenant_is_limited(v_tenant_id) THEN
    PERFORM pg_advisory_xact_lock(hashtextextended(v_tenant_id::text, 0));
    IF EXISTS (SELECT 1 FROM projects.projects AS p WHERE p.tenant_id = v_tenant_id) THEN
        RAISE EXCEPTION 'Przed opłaceniem abonamentu pracownia może mieć jeden projekt domu.'
            USING ERRCODE = 'U1057';
    END IF;
END IF;

Many companies in one database: RLS with FORCE

Every studio table has tenant_id and row-level security. The key word is FORCE - without it the table's owner (that is, our SECURITY DEFINER procedures) bypasses the policies.

SQL
ALTER TABLE projects.projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects.projects FORCE ROW LEVEL SECURITY;

CREATE POLICY projects_read ON projects.projects FOR SELECT
    USING (
        tenant_id = (SELECT platform.actor_tenant_id())
        OR (status = 'published'
            AND EXISTS (SELECT 1 FROM identity.tenants AS t WHERE t.id = tenant_id AND t.status = 'active'))
    );

CREATE POLICY projects_write ON projects.projects FOR ALL
    USING (tenant_id = (SELECT platform.actor_tenant_id()))
    WITH CHECK (tenant_id = (SELECT platform.actor_tenant_id()));

Even if I forget WHERE tenant_id = … in a procedure, the database won't show someone else's rows.

The trap: (SELECT …) around the function

That one pair of parentheses was worth 17 seconds. The first version of the policies looked like this:

SQL
USING (tenant_id = platform.actor_tenant_id())          -- wrong

actor_tenant_id() is SECURITY DEFINER, so the planner doesn't inline it and doesn't know it returns the same value for every row. It calls it for every row, and the (tenant_id, …) index lies idle. On top of that there was a session_user <> 'app_api' policy for the migrations, joined with the rest by OR - goodbye, Index Scan.

Wrapped in a sub-select, the function becomes an InitPlan - evaluated once per query, its result an ordinary parameter of an index condition:

SQL
USING (tenant_id = (SELECT platform.actor_tenant_id()))  -- right

Measured on test data (1000 studios, the biggest with 40 000 designs, ~2 million photos), warm cache:

Readbeforeafter
a studio's designs (200)3 178 ms13 ms
a studio's accounts613 ms1.6 ms
public offer, page 13 023 ms57 ms

The second surprise: once the per-row sub-queries of the views (cover, photo count) pushed the estimated cost over jit_above_cost, PostgreSQL spent 1.6 s JIT-compiling a query that runs in 0.1 s. The fix is one line:

SQL
ALTER ROLE app_api SET jit = off;

So it doesn't come back, a pre-commit script rejects a changeset whose policy or view calls platform.actor_*() outside (SELECT …) or tests session_user. A rule in CI beats a rule in someone's head.

Blazor: the server renders, the browser only displays

The front is Blazor without WebAssembly, with two modes in one application:

  • static SSR for everything public - the home page, a studio's offer, a design's page, FAQ, the purchase - and for signing in (only a plain HTTP request can write the auth cookie). Plain HTML, a fast first render, good SEO, no SignalR for an anonymous visitor;
  • Interactive Server (a circuit over SignalR) for the panels behind sign-in - the design editor, the photo gallery, lists with filters.

The choice of mode lives in one place, App.razor:

razor
<HeadOutlet @rendermode="PageRenderMode" />
<Routes @rendermode="PageRenderMode" />

@code {
    // No prerendering: a page loads its data once, in the circuit, with the signed-in user's token.
    private static readonly IComponentRenderMode Interactive =
        new InteractiveServerRenderMode(prerender: false);

    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = null!;

    // The sign-in page is static SSR: it writes the cookie, which a circuit cannot.
    private IComponentRenderMode? PageRenderMode =>
        HttpContext.AcceptsInteractiveRouting() ? Interactive : null;
}

A public page has @attribute [ExcludeFromInteractiveRouting] at the top and gets null, that is plain SSR; the rest of the application is interactive. prerender: false is deliberate: with prerendering every page would query the database twice (once in SSR, once after the circuit connects).

Where interactivity gets in the way - the payment form, the cookie consent, the redirect to the payment gateway - a plain <form method="post"> with enhanced navigation turned off:

razor
<form method="post" action="consent" data-enhance="false">
    <input type="hidden" name="choice" value="@CookieConsent.Analytics" />
    <input type="hidden" name="returnUrl" value="@ReturnUrl" />
    <button type="submit" class="btn btn-primary">Akceptuję</button>
</form>

Components take ids from Guid.CreateVersion7(), call a procedure and show the database's error 1:1 - the message from RAISE EXCEPTION is already written for people. For errors the procedure doesn't catch yet (CHECK, NOT NULL, a unique index) there is a map by SQLSTATE (shortened):

C#
var message = sqlState switch
{
    "23502" => $"Brakuje wymaganej wartości: {column ?? "pole"}.",
    "23505" => $"Taka wartość już istnieje ({constraint}).",
    "23503" => $"Powiązany rekord nie istnieje albo jest jeszcze używany ({constraint}).",
    "22001" => "Tekst jest za długi.",
    _ when sqlState.StartsWith("U1") => detail,   // the procedure's message
    _ => "Coś poszło nie tak. Spróbuj jeszcze raz.",
};

The rule: the user never sees a bare "the request is not valid" - always what and where.

Tailwind 4 without a JS bundler

Tailwind 4 is one CSS file with @import "tailwindcss" and @theme - no tailwind.config.js. It fits Blazor perfectly: no Vite, no webpack, just the CLI.

css
@import "tailwindcss";
@source "../Components";                      /* scan the .razor files */

@custom-variant dark (&:is(.dark *));

@theme inline {
  --font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
  --font-display: "Bricolage Grotesque", "Inter", sans-serif;
  --color-primary: var(--primary);
  --color-muted-foreground: var(--muted-foreground);
  --radius-lg: var(--radius);
  /* … */
}

:root {
  --radius: 0.625rem;
  --primary: oklch(0.43 0.118 256.5);
  --background: oklch(0.975 0.004 250);
}

Tokens in oklch, shadcn-style names (bg-primary, text-muted-foreground) - the Razor markup looks like any modern front end. The dark theme is a .dark class on <html> and a second set of variables.

The CSS build sits in the csproj, so dotnet build and dotnet watch do everything, and MSBuild rebuilds the CSS only when a .razor file or app.css changes:

xml
<ItemGroup>
  <TailwindInput Include="Styles/app.css;Components/**/*.razor" />
</ItemGroup>
<Target Name="TailwindBuild" BeforeTargets="BeforeBuild"
        Condition="'$(SkipTailwind)' != 'true' And Exists('node_modules/.bin/tailwindcss')"
        Inputs="@(TailwindInput)" Outputs="wwwroot/css/app.css">
  <Exec Command="npm run build:css --silent" />
</Target>

package.json has two dependencies: tailwindcss and @tailwindcss/cli. Zero JavaScript at runtime besides blazor.web.js and one small gallery script.

Tests: a real PostgreSQL, zero mocks

With the logic in the database, mocking the database makes no sense. The tests are xUnit v3 + Testcontainers: PostgreSQL 18 starts, Liquibase applies every changeset, then the tests call the application over HTTP. For each procedure: success, every validation, 409 on a stale version, 404 on a missing row. Plus isolation tests: studio A's admin sees nothing of studio B, not even through the public views.

Migrations are Liquibase with two kinds of files:

  • dated changesets for tables (2026/1-ddl/20261030-03-…sql) - applied once, never edited,
  • runOnChange for procedures and views - one file per object, edited in place, CREATE OR REPLACE.

A procedure's diff in a PR is a diff of one file, not "yet another migration 0147 with the whole procedure copied again".

What I'd tell myself at the start

The good:

  • a business rule lives in one place and holds for every client of the database,
  • RLS with FORCE is a safety belt you can't "forget" in a new endpoint,
  • xmin, idempotent ids and SQLSTATEs give you 409/404/422 with practically no C#,
  • Blazor + Tailwind 4 is one project, one dotnet run, zero front-end toolchain.

The bad, and what you need to know:

  • PL/pgSQL is not C# - debugging means RAISE NOTICE and EXPLAIN (ANALYZE, BUFFERS),
  • RLS can kill performance if you don't know about InitPlan and (SELECT …) - measure on big data before production, not after,
  • Interactive Server keeps state on the server - when the connection drops the user sees a reconnect modal,
  • the rules have to be enforced by a script (pre-commit, tests on pg_policies), because a convention in the README is not enough.

Is it for everyone? No. But for a back office with many companies, forms and rules like "don't publish without a cover" - it's the most boring and most predictable stack I've worked with. Which is exactly the point.