Progmasoft Git

progmaweb

The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.

Clonegit clone https://git.progmasoft.com/progmaweb

Keep accounts and sessions in PostgreSQL

The account API kept everything in the memory of its process, so every
restart and every deployment of the API deleted all accounts and signed
everyone out.

PostgresAccountStore implements IAccountStore on PostgreSQL through Npgsql.
The three uniqueness rules are unique constraints, so two requests that race
for one name, address or Google identity are decided by the database. A
refused account is an ordinary answer, not an exception, and the rules are
reported in the order the in-memory store reports them. A session refers to
its account, and a session of an account that is not stored is refused; the
in-memory store now refuses it as well.

The schema is a list of numbered steps. The service takes the missing ones
when it starts, in one transaction under an advisory lock, and does not
start when the database cannot be reached or is newer than the release.
/health answers 503 while the database does not answer.

ConnectionStrings:Accounts selects PostgreSQL. A production service that is
given no database does not start; keeping accounts in memory there has to
be asked for with Accounts:Store=Memory. Development and the tests keep the
in-memory store by default.

The store gains RemoveExpiredSessionsAsync, and a background service calls
it at the start and once an hour: a session whose token is never presented
again no longer keeps its row for ever.

PostgreSQL keeps a timestamp to the microsecond. The store cuts a moment to
that precision and returns what it stored, and the service uses the
returned account, so the creation time in the registration response equals
the one every later read returns.

Tests. AccountStoreContractTests states the rules once and runs them on
both stores. Further tests cover the schema steps applied concurrently and a
database that is too new, the choice of the store from the configuration,
the removal of expired sessions, and an account with its session surviving
a restart of the service over HTTP. The PostgreSQL tests read their
database from PROGMAWEB_TEST_POSTGRES and work in a schema of their own
each. Without the variable they are skipped; CI starts PostgreSQL 16 for
them, and a test fails the run when the variable is missing there.

Operations. ops/README.md describes the database: the Unix socket with peer
authentication, so that no password exists, the one-time preparation, and
rollback across a schema step. The service unit starts after PostgreSQL.
docs/LIMITATIONS.md no longer lists the in-memory store and now lists the
missing backup and the missing deletion of accounts.
Commit
1c986ff99b3c8f349e4a63c0e922276ddf7dc836
Author
Leitwolf11 ·
Parents
933244cc0fa1

Files · Download .tar.gz

Changes

 .github/workflows/backend.yml                 |  17 ++
 README.md                                     |   2 +-
 apps/api-tests/AccountApiFactory.cs           |  18 +-
 apps/api-tests/AccountServiceTests.cs         |   3 +
 apps/api-tests/AccountStoreContractTests.cs   | 345 ++++++++++++++++++++++++++
 apps/api-tests/AccountStoreSelectionTests.cs  | 273 ++++++++++++++++++++
 apps/api-tests/PostgresTestDatabase.cs        |  87 +++++++
 apps/api-tests/packages.lock.json             | 293 +---------------------
 apps/api/Accounts/AccountSchema.cs            | 133 ++++++++++
 apps/api/Accounts/AccountService.cs           |   5 +-
 apps/api/Accounts/AccountStoreRegistration.cs | 253 +++++++++++++++++++
 apps/api/Accounts/IAccountStore.cs            |   9 +-
 apps/api/Accounts/InMemoryAccountStore.cs     |  28 ++-
 apps/api/Accounts/PostgresAccountStore.cs     | 200 +++++++++++++++
 apps/api/Progmaweb.Api.csproj                 |   1 +
 apps/api/Program.cs                           |   9 +-
 apps/api/packages.lock.json                   |   6 +
 docs/ARCHITECTURE.md                          |   4 +-
 docs/DEVELOPMENT.md                           |  16 +-
 docs/LIMITATIONS.md                           |  23 +-
 ops/README.md                                 |  51 +++-
 ops/systemd/progmaweb-api.service             |   7 +-
 22 files changed, 1461 insertions(+), 322 deletions(-)

diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml
index 6504906..d7b62a4 100644
--- a/.github/workflows/backend.yml
+++ b/.github/workflows/backend.yml
@@ -36,6 +36,23 @@ jobs:
   verify:
     runs-on: ubuntu-latest
     timeout-minutes: 15
+    # The PostgreSQL account store is tested against a real server of the major version production runs. The
+    # container lives for this job only and accepts local connections without a password, so the workflow holds
+    # no credential. Without the variable below the database tests would be skipped; a test fails the run then.
+    services:
+      postgres:
+        image: postgres:16
+        env:
+          POSTGRES_HOST_AUTH_METHOD: trust
+        ports:
+          - 5432:5432
+        options: >-
+          --health-cmd "pg_isready --username postgres"
+          --health-interval 5s
+          --health-timeout 5s
+          --health-retries 20
+    env:
+      PROGMAWEB_TEST_POSTGRES: Host=127.0.0.1;Port=5432;Database=postgres;Username=postgres
     steps:
       - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
       - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5
diff --git a/README.md b/README.md
index d5b05eb..9a1d752 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ menu is remembered across the three hosts. Hebrew text runs right to left while
 - [Localization](docs/LOCALIZATION.md): language selection, text direction and adding a language.
 - [Development](docs/DEVELOPMENT.md): local setup, checks and what CI enforces.
 - [Known limitations](docs/LIMITATIONS.md): what is missing or temporary. Read this before operating the service;
-  accounts are currently kept in memory and do not survive a restart of the API.
+  accounts and sessions are kept in PostgreSQL and survive a restart of the API.
 - [Operations](ops/README.md) and the [mail boundary](ops/mail/README.md).
 
 ## Architecture
diff --git a/apps/api-tests/AccountApiFactory.cs b/apps/api-tests/AccountApiFactory.cs
index 89faa3e..4692f0c 100644
--- a/apps/api-tests/AccountApiFactory.cs
+++ b/apps/api-tests/AccountApiFactory.cs
@@ -11,11 +11,25 @@ namespace Progmasoft.Progmaweb.Api.Tests;
 /// <param name="configureGoogle">
 /// Whether the Google client is configured. Without it the service has to run and refuse only Google sign-in.
 /// </param>
-internal sealed class AccountApiFactory(bool configureGoogle = true) : WebApplicationFactory<Program>
+/// <param name="accountDatabase">
+/// Connection string of the PostgreSQL database that keeps the accounts; <see langword="null"/> keeps them in memory.
+/// </param>
+/// <param name="environment">Name of the hosting environment.</param>
+/// <param name="accountStore">Value of <c>Accounts:Store</c>; <see langword="null"/> leaves it unset.</param>
+internal sealed class AccountApiFactory(
+    bool configureGoogle = true,
+    string? accountDatabase = null,
+    string environment = "Testing",
+    string? accountStore = null) : WebApplicationFactory<Program>
 {
     protected override void ConfigureWebHost(IWebHostBuilder builder)
     {
-        builder.UseEnvironment("Testing");
+        builder.UseEnvironment(environment);
+
+        // The program chooses the store while it registers services, so these are host settings as well. An empty
+        // value overrides a database the environment of the test run names.
+        builder.UseSetting("ConnectionStrings:Accounts", accountDatabase ?? string.Empty);
+        builder.UseSetting("Accounts:Store", accountStore ?? string.Empty);
 
         // The program decides while it registers services whether the Google scheme exists, so these two values
         // have to be host settings: configuration sources added below are applied only when the host is built,
diff --git a/apps/api-tests/AccountServiceTests.cs b/apps/api-tests/AccountServiceTests.cs
index c2a9a46..28fd44f 100644
--- a/apps/api-tests/AccountServiceTests.cs
+++ b/apps/api-tests/AccountServiceTests.cs
@@ -169,5 +169,8 @@ public sealed class AccountServiceTests
 
         public ValueTask RevokeSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken) =>
             ValueTask.CompletedTask;
+
+        public ValueTask<int> RemoveExpiredSessionsAsync(DateTimeOffset now, CancellationToken cancellationToken) =>
+            ValueTask.FromResult(0);
     }
 }
diff --git a/apps/api-tests/AccountStoreContractTests.cs b/apps/api-tests/AccountStoreContractTests.cs
new file mode 100644
index 0000000..2266273
--- /dev/null
+++ b/apps/api-tests/AccountStoreContractTests.cs
@@ -0,0 +1,345 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Npgsql;
+using Progmasoft.Progmaweb.Api.Accounts;
+
+namespace Progmasoft.Progmaweb.Api.Tests;
+
+/// <summary>The rules every <see cref="IAccountStore"/> keeps, run against each implementation.</summary>
+/// <remarks>
+/// The in-memory store and the PostgreSQL store have to behave alike, because the service tests run on the first
+/// and production runs on the second. One set of tests states the rules; a subclass supplies the store.
+/// </remarks>
+public abstract class AccountStoreContractTests
+{
+    /// <summary>A moment with a fraction PostgreSQL cannot keep: seven digits where it keeps six.</summary>
+    private static readonly DateTimeOffset Moment = new DateTimeOffset(2026, 10, 6, 12, 30, 15, TimeSpan.Zero).AddTicks(1234567);
+
+    private static CancellationToken Cancellation => TestContext.Current.CancellationToken;
+
+    /// <summary>Creates an empty store. A subclass without its database skips the test here.</summary>
+    private protected abstract ValueTask<IAccountStore> CreateStoreAsync();
+
+    private static AccountRecord Account(string name, string email, string? googleSubject = null, string? passwordHash = "hash") =>
+        new(
+            Guid.NewGuid(),
+            name,
+            name.ToUpperInvariant(),
+            email,
+            email.ToUpperInvariant(),
+            googleSubject,
+            passwordHash,
+            Moment);
+
+    private static byte[] Digest(byte seed) => [.. Enumerable.Range(0, 32).Select(index => (byte)(seed + index))];
+
+    [Fact]
+    public async Task AStoredAccountIsFoundByEachOfItsKeys()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        AccountRecord account = Account("Ada", "ada@example.com", googleSubject: "google-ada", passwordHash: null);
+
+        CreateAccountResult result = await store.CreateAsync(account, Cancellation);
+
+        Assert.Equal(CreateAccountStatus.Created, result.Status);
+        AccountRecord stored = Assert.IsType<AccountRecord>(result.Account);
+        Assert.Equal(account with { CreatedAt = stored.CreatedAt }, stored);
+        // What the store returns is what it keeps: a later read gives the same moment, to the last digit.
+        Assert.True((account.CreatedAt - stored.CreatedAt).Duration() < TimeSpan.FromMicroseconds(1));
+        Assert.Equal(stored, await store.FindByIdAsync(account.Id, Cancellation));
+        Assert.Equal(stored, await store.FindByEmailAsync("ADA@EXAMPLE.COM", Cancellation));
+        Assert.Equal(stored, await store.FindByGoogleSubjectAsync("google-ada", Cancellation));
+    }
+
+    [Fact]
+    public async Task AnAccountWithoutAGoogleIdentityKeepsItsPasswordHash()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        AccountRecord account = Account("Grace", "grace@example.com", passwordHash: "AQAAAA-hash");
+
+        await store.CreateAsync(account, Cancellation);
+
+        AccountRecord found = Assert.IsType<AccountRecord>(await store.FindByIdAsync(account.Id, Cancellation));
+        Assert.Null(found.GoogleSubject);
+        Assert.Equal("AQAAAA-hash", found.PasswordHash);
+        Assert.Equal("Grace", found.AccountName);
+        Assert.Equal("grace@example.com", found.Email);
+    }
+
+    [Fact]
+    public async Task UnknownKeysFindNothing()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        await store.CreateAsync(Account("Known", "known@example.com"), Cancellation);
+
+        Assert.Null(await store.FindByIdAsync(Guid.NewGuid(), Cancellation));
+        Assert.Null(await store.FindByEmailAsync("OTHER@EXAMPLE.COM", Cancellation));
+        // The lookup key is the normalized address; the spelling the owner entered is not a key.
+        Assert.Null(await store.FindByEmailAsync("known@example.com", Cancellation));
+        Assert.Null(await store.FindByGoogleSubjectAsync("google-nobody", Cancellation));
+    }
+
+    [Fact]
+    public async Task ATakenNameAddressOrGoogleIdentityIsRefusedAndNothingIsStored()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        await store.CreateAsync(Account("Taken", "taken@example.com", "google-taken"), Cancellation);
+
+        AccountRecord sameName = Account("TAKEN", "one@example.com", "google-one");
+        AccountRecord sameEmail = Account("Two", "Taken@Example.com", "google-two");
+        AccountRecord sameGoogle = Account("Three", "three@example.com", "google-taken");
+
+        Assert.Equal(CreateAccountStatus.AccountNameUnavailable, (await store.CreateAsync(sameName, Cancellation)).Status);
+        Assert.Equal(CreateAccountStatus.EmailUnavailable, (await store.CreateAsync(sameEmail, Cancellation)).Status);
+        Assert.Equal(CreateAccountStatus.GoogleSubjectUnavailable, (await store.CreateAsync(sameGoogle, Cancellation)).Status);
+
+        foreach (AccountRecord refused in new[] { sameName, sameEmail, sameGoogle })
+        {
+            Assert.Null(await store.FindByIdAsync(refused.Id, Cancellation));
+        }
+        // A refused account leaves its free keys free.
+        Assert.Null(await store.FindByEmailAsync("ONE@EXAMPLE.COM", Cancellation));
+        Assert.Null(await store.FindByGoogleSubjectAsync("google-two", Cancellation));
+        Assert.Equal(
+            CreateAccountStatus.Created,
+            (await store.CreateAsync(Account("One", "one@example.com", "google-two"), Cancellation)).Status);
+    }
+
+    [Fact]
+    public async Task SeveralBrokenRulesAreReportedInOneFixedOrder()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        await store.CreateAsync(Account("Taken", "taken@example.com", "google-taken"), Cancellation);
+
+        // Google identity before name, name before address, whichever the store happens to check first.
+        Assert.Equal(
+            CreateAccountStatus.GoogleSubjectUnavailable,
+            (await store.CreateAsync(Account("Taken", "taken@example.com", "google-taken"), Cancellation)).Status);
+        Assert.Equal(
+            CreateAccountStatus.AccountNameUnavailable,
+            (await store.CreateAsync(Account("Taken", "taken@example.com", "google-free"), Cancellation)).Status);
+        Assert.Equal(
+            CreateAccountStatus.AccountNameUnavailable,
+            (await store.CreateAsync(Account("Taken", "taken@example.com"), Cancellation)).Status);
+        Assert.Equal(
+            CreateAccountStatus.EmailUnavailable,
+            (await store.CreateAsync(Account("Free", "taken@example.com"), Cancellation)).Status);
+    }
+
+    [Fact]
+    public async Task ManyAccountsMayBeWithoutAGoogleIdentity()
+    {
+        IAccountStore store = await CreateStoreAsync();
+
+        for (int index = 0; index < 5; index++)
+        {
+            CreateAccountResult result =
+                await store.CreateAsync(Account($"User{index}", $"user{index}@example.com"), Cancellation);
+            Assert.Equal(CreateAccountStatus.Created, result.Status);
+        }
+    }
+
+    [Fact]
+    public async Task OfManyRequestsForOneNameExactlyOneIsStored()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        AccountRecord[] candidates = [.. Enumerable.Range(0, 16).Select(index => Account("Race", $"race{index}@example.com"))];
+
+        CreateAccountResult[] results = await Task.WhenAll(
+            candidates.Select(candidate => Task.Run(async () => await store.CreateAsync(candidate, Cancellation))));
+
+        CreateAccountResult winner = Assert.Single(results, result => result.Status is CreateAccountStatus.Created);
+        Assert.All(
+            results.Where(result => !ReferenceEquals(result, winner)),
+            result => Assert.Equal(CreateAccountStatus.AccountNameUnavailable, result.Status));
+        foreach (AccountRecord candidate in candidates)
+        {
+            AccountRecord? found = await store.FindByIdAsync(candidate.Id, Cancellation);
+            Assert.Equal(candidate.Id == winner.Account!.Id, found is not null);
+        }
+    }
+
+    [Fact]
+    public async Task ASessionIsStoredFoundReplacedAndRevoked()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        AccountRecord first = Account("First", "first@example.com");
+        AccountRecord second = Account("Second", "second@example.com");
+        await store.CreateAsync(first, Cancellation);
+        await store.CreateAsync(second, Cancellation);
+        DateTimeOffset created = new(2026, 10, 6, 8, 0, 0, TimeSpan.Zero);
+        SessionRecord session = new(Digest(1), first.Id, created, created.AddHours(12));
+
+        Assert.Null(await store.FindSessionAsync(Digest(1), Cancellation));
+        await store.StoreSessionAsync(session, Cancellation);
+
+        SessionRecord found = Assert.IsType<SessionRecord>(await store.FindSessionAsync(Digest(1), Cancellation));
+        Assert.Equal(session.TokenDigest, found.TokenDigest);
+        Assert.Equal(first.Id, found.AccountId);
+        Assert.Equal(session.CreatedAt, found.CreatedAt);
+        Assert.Equal(session.ExpiresAt, found.ExpiresAt);
+        Assert.Null(await store.FindSessionAsync(Digest(2), Cancellation));
+
+        // Storing the same digest again replaces the session.
+        await store.StoreSessionAsync(session with { AccountId = second.Id, ExpiresAt = created.AddHours(1) }, Cancellation);
+        SessionRecord replaced = Assert.IsType<SessionRecord>(await store.FindSessionAsync(Digest(1), Cancellation));
+        Assert.Equal(second.Id, replaced.AccountId);
+        Assert.Equal(created.AddHours(1), replaced.ExpiresAt);
+
+        await store.RevokeSessionAsync(Digest(1), Cancellation);
+        Assert.Null(await store.FindSessionAsync(Digest(1), Cancellation));
+        // Revoking again, or revoking what never existed, is not an error.
+        await store.RevokeSessionAsync(Digest(1), Cancellation);
+        await store.RevokeSessionAsync(Digest(9), Cancellation);
+    }
+
+    [Fact]
+    public async Task ASessionOfAnAccountThatIsNotStoredIsRefused()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        DateTimeOffset created = new(2026, 10, 6, 8, 0, 0, TimeSpan.Zero);
+        SessionRecord orphan = new(Digest(3), Guid.NewGuid(), created, created.AddHours(1));
+
+        await Assert.ThrowsAnyAsync<Exception>(async () => await store.StoreSessionAsync(orphan, Cancellation));
+
+        Assert.Null(await store.FindSessionAsync(Digest(3), Cancellation));
+    }
+
+    [Fact]
+    public async Task OnlyExpiredSessionsAreRemoved()
+    {
+        IAccountStore store = await CreateStoreAsync();
+        AccountRecord account = Account("Owner", "owner@example.com");
+        await store.CreateAsync(account, Cancellation);
+        DateTimeOffset now = new(2026, 10, 6, 12, 0, 0, TimeSpan.Zero);
+        await store.StoreSessionAsync(new SessionRecord(Digest(10), account.Id, now.AddHours(-13), now.AddHours(-1)), Cancellation);
+        // A session expires at its expiry, not after it.
+        await store.StoreSessionAsync(new SessionRecord(Digest(20), account.Id, now.AddHours(-12), now), Cancellation);
+        await store.StoreSessionAsync(new SessionRecord(Digest(30), account.Id, now.AddHours(-1), now.AddTicks(10)), Cancellation);
+        await store.StoreSessionAsync(new SessionRecord(Digest(40), account.Id, now, now.AddHours(12)), Cancellation);
+
+        Assert.Equal(2, await store.RemoveExpiredSessionsAsync(now, Cancellation));
+
+        Assert.Null(await store.FindSessionAsync(Digest(10), Cancellation));
+        Assert.Null(await store.FindSessionAsync(Digest(20), Cancellation));
+        Assert.NotNull(await store.FindSessionAsync(Digest(30), Cancellation));
+        Assert.NotNull(await store.FindSessionAsync(Digest(40), Cancellation));
+        Assert.Equal(0, await store.RemoveExpiredSessionsAsync(now, Cancellation));
+        // The account outlives its sessions.
+        Assert.NotNull(await store.FindByIdAsync(account.Id, Cancellation));
+    }
+}
+
+public sealed class InMemoryAccountStoreTests : AccountStoreContractTests
+{
+    private protected override ValueTask<IAccountStore> CreateStoreAsync() =>
+        ValueTask.FromResult<IAccountStore>(new InMemoryAccountStore());
+}
+
+public sealed class PostgresAccountStoreTests : AccountStoreContractTests, IAsyncDisposable
+{
+    private PostgresTestDatabase? database;
+    private NpgsqlDataSource? dataSource;
+
+    private protected override async ValueTask<IAccountStore> CreateStoreAsync()
+    {
+        database = await PostgresTestDatabase.CreateAsync();
+        dataSource = database.OpenDataSource();
+        await AccountSchema.ApplyAsync(dataSource, TestContext.Current.CancellationToken);
+        return new PostgresAccountStore(dataSource);
+    }
+
+    public async ValueTask DisposeAsync()
+    {
+        if (dataSource is not null)
+        {
+            await dataSource.DisposeAsync();
+        }
+
+        if (database is not null)
+        {
+            await database.DisposeAsync();
+        }
+    }
+
+    [Fact]
+    public async Task WhatOneProcessStoredAnotherProcessFinds()
+    {
+        IAccountStore first = await CreateStoreAsync();
+        AccountRecord account = new(
+            Guid.NewGuid(), "Durable", "DURABLE", "durable@example.com", "DURABLE@EXAMPLE.COM", null, "hash",
+            new DateTimeOffset(2026, 10, 6, 9, 0, 0, TimeSpan.Zero));
+        byte[] digest = [.. Enumerable.Repeat((byte)7, 32)];
+        await first.CreateAsync(account, TestContext.Current.CancellationToken);
+        await first.StoreSessionAsync(
+            new SessionRecord(digest, account.Id, account.CreatedAt, account.CreatedAt.AddHours(12)),
+            TestContext.Current.CancellationToken);
+
+        // A second pool of connections stands for the service after a restart: it shares nothing with the first
+        // but the database.
+        await dataSource!.DisposeAsync();
+        dataSource = database!.OpenDataSource();
+        PostgresAccountStore second = new(dataSource);
+
+        Assert.Equal(account, await second.FindByIdAsync(account.Id, TestContext.Current.CancellationToken));
+        SessionRecord session = Assert.IsType<SessionRecord>(
+            await second.FindSessionAsync(digest, TestContext.Current.CancellationToken));
+        Assert.Equal(account.Id, session.AccountId);
+        Assert.Equal(
+            CreateAccountStatus.AccountNameUnavailable,
+            (await second.CreateAsync(account with { Id = Guid.NewGuid(), Email = "x@example.com", NormalizedEmail = "X@EXAMPLE.COM" },
+                TestContext.Current.CancellationToken)).Status);
+    }
+
+    [Fact]
+    public async Task TheSchemaIsAppliedOnceHoweverOftenAndHoweverConcurrentlyItIsAsked()
+    {
+        await using PostgresTestDatabase fresh = await PostgresTestDatabase.CreateAsync();
+        await using NpgsqlDataSource source = fresh.OpenDataSource();
+
+        int[] taken = await Task.WhenAll(Enumerable.Range(0, 6).Select(_ =>
+            Task.Run(() => AccountSchema.ApplyAsync(source, TestContext.Current.CancellationToken))));
+
+        // Processes that start together wait for one another; one of them takes every step and the rest none.
+        Assert.Equal(AccountSchema.CurrentVersion, taken.Sum());
+        Assert.Equal(0, await AccountSchema.ApplyAsync(source, TestContext.Current.CancellationToken));
+        await using NpgsqlCommand versions = source.CreateCommand("SELECT count(*), max(version) FROM account_schema_versions");
+        await using NpgsqlDataReader reader = await versions.ExecuteReaderAsync(TestContext.Current.CancellationToken);
+        await reader.ReadAsync(TestContext.Current.CancellationToken);
+        Assert.Equal(AccountSchema.CurrentVersion, reader.GetInt64(0));
+        Assert.Equal(AccountSchema.CurrentVersion, reader.GetInt32(1));
+    }
+
+    [Fact]
+    public async Task ADatabaseNewerThanTheProgramIsRefusedAndLeftAsItIs()
+    {
+        await using PostgresTestDatabase fresh = await PostgresTestDatabase.CreateAsync();
+        await using NpgsqlDataSource source = fresh.OpenDataSource();
+        await AccountSchema.ApplyAsync(source, TestContext.Current.CancellationToken);
+        await using (NpgsqlCommand future = source.CreateCommand("INSERT INTO account_schema_versions (version) VALUES ($1)"))
+        {
+            future.Parameters.AddWithValue(AccountSchema.CurrentVersion + 1);
+            await future.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
+        }
+
+        InvalidOperationException refused = await Assert.ThrowsAsync<InvalidOperationException>(
+            () => AccountSchema.ApplyAsync(source, TestContext.Current.CancellationToken));
+
+        Assert.Contains("schema version", refused.Message, StringComparison.Ordinal);
+        await using NpgsqlCommand count = source.CreateCommand("SELECT count(*) FROM accounts");
+        Assert.Equal(0L, await count.ExecuteScalarAsync(TestContext.Current.CancellationToken));
+    }
+
+    [Fact]
+    public void AMomentIsCutToTheMicrosecondInUtc()
+    {
+        DateTimeOffset local = new DateTimeOffset(2026, 10, 6, 15, 30, 0, TimeSpan.FromHours(3)).AddTicks(1234567);
+
+        DateTimeOffset stored = PostgresAccountStore.ToStoredPrecision(local);
+
+        Assert.Equal(TimeSpan.Zero, stored.Offset);
+        Assert.Equal(new DateTimeOffset(2026, 10, 6, 12, 30, 0, TimeSpan.Zero).AddTicks(1234560), stored);
+        Assert.Equal(stored, PostgresAccountStore.ToStoredPrecision(stored));
+    }
+}
diff --git a/apps/api-tests/AccountStoreSelectionTests.cs b/apps/api-tests/AccountStoreSelectionTests.cs
new file mode 100644
index 0000000..e9724c0
--- /dev/null
+++ b/apps/api-tests/AccountStoreSelectionTests.cs
@@ -0,0 +1,273 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using System.Net;
+using System.Net.Http.Json;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging.Abstractions;
+using Progmasoft.Progmaweb.Api.Accounts;
+
+namespace Progmasoft.Progmaweb.Api.Tests;
+
+public sealed class AccountStoreSelectionTests
+{
+    private const string Database = "Host=/var/run/postgresql;Database=progmaweb;Username=progmaweb";
+
+    private static IConfiguration Configuration(string? store, string? connectionString) =>
+        new ConfigurationBuilder()
+            .AddInMemoryCollection(new Dictionary<string, string?>
+            {
+                [AccountStoreRegistration.StoreKey] = store,
+                ["ConnectionStrings:Accounts"] = connectionString
+            })
+            .Build();
+
+    [Theory]
+    [InlineData(null, Database, false, AccountStoreKind.PostgreSql)]
+    [InlineData(null, Database, true, AccountStoreKind.PostgreSql)]
+    [InlineData("PostgreSQL", Database, true, AccountStoreKind.PostgreSql)]
+    [InlineData("postgresql", Database, false, AccountStoreKind.PostgreSql)]
+    [InlineData(null, null, false, AccountStoreKind.Memory)]
+    [InlineData("", "  ", false, AccountStoreKind.Memory)]
+    [InlineData("Memory", null, false, AccountStoreKind.Memory)]
+    [InlineData("memory", null, true, AccountStoreKind.Memory)]
+    internal void TheConfigurationSelectsTheStore(
+        string? store,
+        string? connectionString,
+        bool isProduction,
+        AccountStoreKind expected)
+    {
+        Assert.Equal(expected, AccountStoreRegistration.Select(Configuration(store, connectionString), isProduction));
+    }
+
+    [Theory]
+    // Production never falls back to memory on its own.
+    [InlineData(null, null, true, "No account database is configured")]
+    [InlineData("", "", true, "No account database is configured")]
+    [InlineData("PostgreSQL", null, false, "is not set")]
+    [InlineData("Memory", Database, false, "Remove one of them")]
+    [InlineData("Sqlite", null, false, "must be PostgreSQL or Memory")]
+    public void AConfigurationThatCannotBeMeantIsRefused(
+        string? store,
+        string? connectionString,
+        bool isProduction,
+        string expectedMessage)
+    {
+        InvalidOperationException refused = Assert.Throws<InvalidOperationException>(
+            () => AccountStoreRegistration.Select(Configuration(store, connectionString), isProduction));
+
+        Assert.Contains(expectedMessage, refused.Message, StringComparison.Ordinal);
+        // A message about the configuration never repeats the connection string.
+        Assert.DoesNotContain("Host=", refused.Message, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public void AProductionServiceWithoutADatabaseDoesNotStart()
+    {
+        using AccountApiFactory factory = new(environment: "Production");
+
+        InvalidOperationException refused = Assert.Throws<InvalidOperationException>(() => factory.CreateAccountClient());
+
+        Assert.Contains("No account database is configured", refused.Message, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task AProductionServiceThatAsksForMemoryStartsAndKeepsAccountsInMemory()
+    {
+        await using AccountApiFactory factory = new(environment: "Production", accountStore: "Memory");
+        using HttpClient client = factory.CreateAccountClient();
+
+        HttpResponseMessage health = await client.GetAsync("/health", TestContext.Current.CancellationToken);
+
+        Assert.Equal(HttpStatusCode.OK, health.StatusCode);
+        Assert.IsType<InMemoryAccountStore>(factory.Services.GetRequiredService<IAccountStore>());
+    }
+
+    [Fact]
+    public async Task TheTestServiceKeepsAccountsInMemoryWithoutBeingAsked()
+    {
+        await using AccountApiFactory factory = new();
+        using HttpClient client = factory.CreateAccountClient();
+        await client.GetAsync("/health", TestContext.Current.CancellationToken);
+
+        Assert.IsType<InMemoryAccountStore>(factory.Services.GetRequiredService<IAccountStore>());
+    }
+}
+
+public sealed class ExpiredSessionCleanupTests
+{
+    private sealed class FixedClock(DateTimeOffset now) : TimeProvider
+    {
+        public override DateTimeOffset GetUtcNow() => now;
+    }
+
+    private sealed class FailingStore : IAccountStore
+    {
+        public int Attempts { get; private set; }
+
+        public ValueTask<int> RemoveExpiredSessionsAsync(DateTimeOffset now, CancellationToken cancellationToken)
+        {
+            Attempts++;
+            throw new IOException("The database does not answer.");
+        }
+
+        public ValueTask<CreateAccountResult> CreateAsync(AccountRecord account, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask<AccountRecord?> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask<AccountRecord?> FindByGoogleSubjectAsync(string googleSubject, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask<AccountRecord?> FindByIdAsync(Guid id, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask StoreSessionAsync(SessionRecord session, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask<SessionRecord?> FindSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+
+        public ValueTask RevokeSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken) =>
+            throw new NotSupportedException();
+    }
+
+    [Fact]
+    public async Task ARemovalTakesWhatHasExpiredByTheClock()
+    {
+        DateTimeOffset now = new(2026, 10, 6, 12, 0, 0, TimeSpan.Zero);
+        InMemoryAccountStore store = new();
+        AccountRecord account = new(Guid.NewGuid(), "Owner", "OWNER", "o@example.com", "O@EXAMPLE.COM", null, "hash", now);
+        await store.CreateAsync(account, TestContext.Current.CancellationToken);
+        byte[] expired = [.. Enumerable.Repeat((byte)1, 32)];
+        byte[] valid = [.. Enumerable.Repeat((byte)2, 32)];
+        await store.StoreSessionAsync(new SessionRecord(expired, account.Id, now.AddHours(-13), now.AddHours(-1)), TestContext.Current.CancellationToken);
+        await store.StoreSessionAsync(new SessionRecord(valid, account.Id, now, now.AddHours(12)), TestContext.Current.CancellationToken);
+        using ExpiredSessionCleanup cleanup = new(store, new FixedClock(now), NullLogger<ExpiredSessionCleanup>.Instance);
+
+        await cleanup.RemoveOnceAsync(TestContext.Current.CancellationToken);
+
+        Assert.Null(await store.FindSessionAsync(expired, TestContext.Current.CancellationToken));
+        Assert.NotNull(await store.FindSessionAsync(valid, TestContext.Current.CancellationToken));
+    }
+
+    [Fact]
+    public async Task ARemovalThatFailsDoesNotStopTheService()
+    {
+        FailingStore store = new();
+        using ExpiredSessionCleanup cleanup = new(store, TimeProvider.System, NullLogger<ExpiredSessionCleanup>.Instance);
+
+        await cleanup.RemoveOnceAsync(TestContext.Current.CancellationToken);
+        await cleanup.RemoveOnceAsync(TestContext.Current.CancellationToken);
+
+        Assert.Equal(2, store.Attempts);
+    }
+
+    [Fact]
+    public async Task ACancelledRemovalIsNotSwallowed()
+    {
+        InMemoryAccountStore store = new();
+        using ExpiredSessionCleanup cleanup = new(store, TimeProvider.System, NullLogger<ExpiredSessionCleanup>.Instance);
+        using CancellationTokenSource cancelled = new();
+        await cancelled.CancelAsync();
+
+        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => cleanup.RemoveOnceAsync(cancelled.Token));
+    }
+}
+
+public sealed class DurableAccountApiTests
+{
+    private static async Task<string> SessionCookieAsync(HttpResponseMessage response)
+    {
+        Assert.True(response.IsSuccessStatusCode, await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
+        string header = Assert.Single(
+            response.Headers.GetValues("Set-Cookie"),
+            value => value.StartsWith("__Host-ProgmasoftSession=", StringComparison.Ordinal));
+        return header[..header.IndexOf(';', StringComparison.Ordinal)];
+    }
+
+    private static HttpRequestMessage Me(string cookie)
+    {
+        HttpRequestMessage request = new(HttpMethod.Get, "/api/v1/accounts/me");
+        request.Headers.Add("Cookie", cookie);
+        return request;
+    }
+
+    [Fact]
+    public async Task AnAccountAndItsSessionSurviveARestartOfTheService()
+    {
+        await using PostgresTestDatabase database = await PostgresTestDatabase.CreateAsync();
+        string cookie;
+
+        await using (AccountApiFactory beforeRestart = new(accountDatabase: database.ConnectionString))
+        {
+            using HttpClient client = beforeRestart.CreateAccountClient(handleCookies: false);
+            HttpResponseMessage registration = await client.PostAsJsonAsync("/api/v1/accounts/register", new
+            {
+                accountName = "Survivor",
+                email = "survivor@example.com",
+                password = "a-long-development-password"
+            }, TestContext.Current.CancellationToken);
+            Assert.Equal(HttpStatusCode.Created, registration.StatusCode);
+            cookie = await SessionCookieAsync(registration);
+            Assert.IsType<PostgresAccountStore>(beforeRestart.Services.GetRequiredService<IAccountStore>());
+        }
+
+        // The first service is gone with everything it held in memory. The second starts on the same database.
+        await using AccountApiFactory afterRestart = new(accountDatabase: database.ConnectionString);
+        using HttpClient restarted = afterRestart.CreateAccountClient(handleCookies: false);
+
+        HttpResponseMessage me = await restarted.SendAsync(Me(cookie), TestContext.Current.CancellationToken);
+        Assert.Equal(HttpStatusCode.OK, me.StatusCode);
+        AccountResponse account = Assert.IsType<AccountResponse>(
+            await me.Content.ReadFromJsonAsync<AccountResponse>(TestContext.Current.CancellationToken));
+        Assert.Equal("Survivor", account.AccountName);
+        Assert.Equal("survivor@example.com", account.Email);
+
+        HttpResponseMessage login = await restarted.PostAsJsonAsync("/api/v1/accounts/login", new
+        {
+            email = "survivor@example.com",
+            password = "a-long-development-password"
+        }, TestContext.Current.CancellationToken);
+        Assert.Equal(HttpStatusCode.OK, login.StatusCode);
+
+        HttpResponseMessage again = await restarted.PostAsJsonAsync("/api/v1/accounts/register", new
+        {
+            accountName = "survivor",
+            email = "other@example.com",
+            password = "a-long-development-password"
+        }, TestContext.Current.CancellationToken);
+        Assert.Equal(HttpStatusCode.BadRequest, again.StatusCode);
+
+        // Signing out removes the session from the database, not only from this process.
+        HttpRequestMessage logout = new(HttpMethod.Post, "/api/v1/accounts/logout");
+        logout.Headers.Add("Cookie", cookie);
+        await restarted.SendAsync(logout, TestContext.Current.CancellationToken);
+        HttpResponseMessage afterLogout = await restarted.SendAsync(Me(cookie), TestContext.Current.CancellationToken);
+        Assert.Equal(HttpStatusCode.Unauthorized, afterLogout.StatusCode);
+    }
+
+    [Fact]
+    public async Task TheHealthEndpointAnswersWhileTheDatabaseDoes()
+    {
+        await using PostgresTestDatabase database = await PostgresTestDatabase.CreateAsync();
+        await using AccountApiFactory factory = new(accountDatabase: database.ConnectionString, environment: "Production");
+        using HttpClient client = factory.CreateAccountClient();
+
+        HttpResponseMessage health = await client.GetAsync("/health", TestContext.Current.CancellationToken);
+
+        Assert.Equal(HttpStatusCode.OK, health.StatusCode);
+    }
+
+    [Fact]
+    public void AServiceWhoseDatabaseCannotBeReachedDoesNotStart()
+    {
+        // Nothing listens on this port of the loopback address; the short timeout keeps the test quick.
+        using AccountApiFactory factory = new(
+            accountDatabase: "Host=127.0.0.1;Port=1;Database=absent;Username=nobody;Timeout=2;Command Timeout=2");
+
+        Assert.ThrowsAny<Exception>(() => factory.CreateAccountClient());
+    }
+}
diff --git a/apps/api-tests/PostgresTestDatabase.cs b/apps/api-tests/PostgresTestDatabase.cs
new file mode 100644
index 0000000..401a69c
--- /dev/null
+++ b/apps/api-tests/PostgresTestDatabase.cs
@@ -0,0 +1,87 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Npgsql;
+
+namespace Progmasoft.Progmaweb.Api.Tests;
+
+/// <summary>A schema of its own in the PostgreSQL database of the test run, removed when the test ends.</summary>
+/// <remarks>
+/// <para>
+/// The tests that need PostgreSQL read its connection string from the environment variable
+/// <see cref="VariableName"/>. The user it names must be allowed to create schemas in its database. Without the
+/// variable those tests are skipped, and <see cref="PostgresConfigurationTests"/> fails the run where skipping
+/// them would hide a gap: in continuous integration.
+/// </para>
+/// <para>
+/// Each test works in a schema with a random name, selected through the search path of its connection string, so
+/// tests neither see nor wait for one another and nothing is left behind.
+/// </para>
+/// </remarks>
+internal sealed class PostgresTestDatabase : IAsyncDisposable
+{
+    /// <summary>Environment variable that holds the connection string of the test database.</summary>
+    public const string VariableName = "PROGMAWEB_TEST_POSTGRES";
+
+    private readonly string administrativeConnectionString;
+    private readonly string schema;
+
+    private PostgresTestDatabase(string administrativeConnectionString, string schema)
+    {
+        this.administrativeConnectionString = administrativeConnectionString;
+        this.schema = schema;
+        ConnectionString = new NpgsqlConnectionStringBuilder(administrativeConnectionString) { SearchPath = schema }
+            .ConnectionString;
+    }
+
+    /// <summary>The connection string of the test database, or <see langword="null"/> when none is configured.</summary>
+    public static string? ConfiguredConnectionString
+    {
+        get
+        {
+            string? value = Environment.GetEnvironmentVariable(VariableName);
+            return string.IsNullOrWhiteSpace(value) ? null : value;
+        }
+    }
+
+    /// <summary>A connection string whose statements run in the schema of this test.</summary>
+    public string ConnectionString { get; }
+
+    /// <summary>Creates the schema of a test; skips the test when no database is configured.</summary>
+    public static async Task<PostgresTestDatabase> CreateAsync()
+    {
+        string? configured = ConfiguredConnectionString;
+        Assert.SkipUnless(configured is not null, $"{VariableName} names no PostgreSQL database.");
+
+        string schema = "test_" + Guid.NewGuid().ToString("N");
+        await using NpgsqlDataSource dataSource = NpgsqlDataSource.Create(configured!);
+        await using NpgsqlCommand command = dataSource.CreateCommand($"CREATE SCHEMA {schema}");
+        await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
+        return new PostgresTestDatabase(configured!, schema);
+    }
+
+    /// <summary>Opens connections to the schema of this test. The caller disposes the data source.</summary>
+    public NpgsqlDataSource OpenDataSource() => NpgsqlDataSource.Create(ConnectionString);
+
+    public async ValueTask DisposeAsync()
+    {
+        // Pooled connections of disposed data sources are closed, so nothing holds the schema.
+        await using NpgsqlDataSource dataSource = NpgsqlDataSource.Create(administrativeConnectionString);
+        await using NpgsqlCommand command = dataSource.CreateCommand($"DROP SCHEMA IF EXISTS {schema} CASCADE");
+        await command.ExecuteNonQueryAsync(CancellationToken.None);
+    }
+}
+
+public sealed class PostgresConfigurationTests
+{
+    [Fact]
+    public void ContinuousIntegrationRunsTheDatabaseTests()
+    {
+        // GitHub Actions sets CI. A run there without the database would report the PostgreSQL tests as skipped and
+        // the run as passed, which is how an untested store would be merged.
+        if (string.Equals(Environment.GetEnvironmentVariable("CI"), "true", StringComparison.OrdinalIgnoreCase))
+        {
+            Assert.NotNull(PostgresTestDatabase.ConfiguredConnectionString);
+        }
+    }
+}
diff --git a/apps/api-tests/packages.lock.json b/apps/api-tests/packages.lock.json
index ca4dbb9..fe3009a 100644
--- a/apps/api-tests/packages.lock.json
+++ b/apps/api-tests/packages.lock.json
@@ -8,8 +8,6 @@
         "resolved": "8.0.0",
         "contentHash": "r3+GPhzJd8G/qlw8UFOYGECZSFvpg0j+yRTGbSr8ikk1ed4Hui+Y56ghPcBT43S3DWYKEzZLGmZ/KFS28k1zHg==",
         "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.1",
-          "Microsoft.Extensions.DependencyInjection": "8.0.1",
           "Microsoft.Testing.Platform": "2.0.2"
         }
       },
@@ -20,8 +18,7 @@
         "contentHash": "BJi3rpYETlh0wd14Lg5Is9MWvEf55TAGd7yo+xGHuEZp7ololyvftbQZ1i7ZuITA7DgNPJED6EMhFSWycq7SBg==",
         "dependencies": {
           "Microsoft.AspNetCore.TestHost": "10.0.11",
-          "Microsoft.Extensions.DependencyModel": "10.0.11",
-          "Microsoft.Extensions.Hosting": "10.0.11"
+          "Microsoft.Extensions.DependencyModel": "10.0.11"
         }
       },
       "xunit.v3.mtp-v2": {
@@ -55,290 +52,11 @@
         "resolved": "6.0.0",
         "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg=="
       },
-      "Microsoft.Extensions.Configuration": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "wlhRqZW8LcJPa+vk2oLAc/REXDItHtkFQdf/QcXYGZbZOO13izcsKY1pCvuFQYwUiZD+hwSZwsKASjqT+BNaVg==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "fVi053xdpda9Em7vSkmgVxO/PtgC2m78ekReKWsgcyskqY0U82Bz/MONwxpGzI0hElYKJfw+fupqMVeKW3fSaA==",
-        "dependencies": {
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.Binder": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "rFn8RuszZn3qquPVkDytMUlPc2+rXl9MCoygwc1XmAgC5vg5/oXJ8hkOosOrLoBLsqdTy4lFwP6iQdPS9uSYOA==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.CommandLine": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "1KHr/1L56llwQ/yI0tAisEA31UpPsn8aasjASIwELOaN4JIUcbjuQBMdFOIzfNBBeULoUa0XfBe5QDtRRUY+fg==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.EnvironmentVariables": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "KICyU3eVi5jvloKm01EXV69L97H/zkhISVtV98cIuzuFOxNx3xTUVcXqvWTz3aq7OvUuDB/MFlPFjmxRaKF7/A==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.FileExtensions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "mDW7KVFB05M6jiRUyaZiOMWhS31n5HlSZwoYctHAZAucD4sMDJ70IxOmkGDt6RpstchD+keWBjhdzcMpSkWvWQ==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Physical": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.Json": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "nSPrT8U/cNoB4coqkmnanAMK9PsL7lsjG+LLUKEwHRFwS6E78b8S1wdv/y88EOxBhasWov1rLd7RTHmmsYPOLg==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Configuration.FileExtensions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Configuration.UserSecrets": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "BRliLdUowglV8GS+J1G/QsSofCJYYFg3U8QZx0ACRn+a91az/Qnpy+h6PyHS94WgV2TSazX5D/cuuk6wnCJatw==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Configuration.Json": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Physical": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.DependencyInjection": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "PSmotV19c7E3lKed++uYo1kSiXFI+uTl37CBSrhq+CfLC3FCHjG7R91+xPnNehQfHS1b0Tzo/CCLPWH3qaEheg==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.DependencyInjection.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "/a1aJz4m7ylhEDf25ugQChLQoN5XwoGjWw/BoR/ZWWKsO1v4DdJElS1uyngahz4B/eOzjFk1KNTkarRLE5wsIg=="
-      },
       "Microsoft.Extensions.DependencyModel": {
         "type": "Transitive",
         "resolved": "10.0.11",
         "contentHash": "PJPtFYsZ+r+uz9qqXWUTEyKeJ1EiBGIJtqavkg9ZXijjGSFAk4Fgi5sqIxj+uAyLZwEKgexDUQXhWhvU6l3+og=="
       },
-      "Microsoft.Extensions.Diagnostics": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "HT70uGPxMLqqnOzKMcnQtDmeV4r0KHr4qVCLhP7SXil9jMEm8sQXwcybxVVFGXZJ1V44xV0mLqQ54aZbcR2OiQ==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Diagnostics.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "se7Kx8QpJEt+nf26L4qIVAofGTDr1wbexxsh/Fm3Xc04xUkqUXK06KUS7FLwSQYSjqb7q9n+T7MEcXYBhI1Y5g==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.FileProviders.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "JOjac6SQQgZmdmB8WGEw61/7siqMZoWJMkmq2p1goJGxqI59lO6oB4bOl0jNsbaPBdYy5Mlkb+6U7T4+CjnD8Q==",
-        "dependencies": {
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.FileProviders.Physical": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "Tq/UqMaczePv9yWwSsJZRgKtgA46djVR5xHj/lZBCueQ3ag8f9v5mu0EdhrNx7tXxNk+Y9OurG2oKuSKINjr0A==",
-        "dependencies": {
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileSystemGlobbing": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.FileSystemGlobbing": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "2i6rtW/B5rCnWCnhdmWWEmaM9O0HD0zsPY9eRqa++y4tclI3Uw8zvGbBvhY/LjAdtf8gUHhUPcAWj3DRlWMXmQ=="
-      },
-      "Microsoft.Extensions.Hosting": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "eIDa/Rl+93aj17gMlFsJJx+LhBvb3CP0Mu1PeVYkDp2Y3S4Jock8UynfGQEcx7lrlq+gKW+ECQJHbro/LTPDEQ==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Configuration.Binder": "10.0.11",
-          "Microsoft.Extensions.Configuration.CommandLine": "10.0.11",
-          "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.11",
-          "Microsoft.Extensions.Configuration.FileExtensions": "10.0.11",
-          "Microsoft.Extensions.Configuration.Json": "10.0.11",
-          "Microsoft.Extensions.Configuration.UserSecrets": "10.0.11",
-          "Microsoft.Extensions.DependencyInjection": "10.0.11",
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Diagnostics": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Physical": "10.0.11",
-          "Microsoft.Extensions.Hosting.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging.Configuration": "10.0.11",
-          "Microsoft.Extensions.Logging.Console": "10.0.11",
-          "Microsoft.Extensions.Logging.Debug": "10.0.11",
-          "Microsoft.Extensions.Logging.EventLog": "10.0.11",
-          "Microsoft.Extensions.Logging.EventSource": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Hosting.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "pwtpF7iF/NNaOBcX+pvMZ7y2+JAVbH5KkNrH9uMZtuVxVJsFTDiWiCR7Tk3HVptsAijaetipUZVRVK2LLq+nvA==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.11",
-          "Microsoft.Extensions.FileProviders.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "nUOJwgFkSiLHiVGFpU22pIJtuWYewuSYQ3JVuP/gdK8ASMT807Px+TYQiRWs6uSsOmoyFTaVCwKXTasczV6BpA==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.Abstractions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "Ljd0Uxoq5XpScD2Bg0nM/r3mwx7Ao5Uq24eo2ARxbGvqJ7Zht6rt2cJtwVRH4Cv+1ZVMdXz6TB43KbpmsxRrvQ==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.Configuration": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "S7LvLeVHKNPaY2NMyxW7c2TBGsLgxoSUBCV5Ev5iN8kgC7EPR2UB7eW7vHsElGMcIUDwRmoxLfvGDynCn3q6EA==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration": "10.0.11",
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Configuration.Binder": "10.0.11",
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11",
-          "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.Console": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "dFc0yDudyD1iIg6z9XT7ofsT3hVO7Y4ylrxGHIVRR0GaZ4CUk4ujOrMoy7wWEdNHZhvJooySg6hZpOxyS8zEVA==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging.Configuration": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.Debug": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "wr+j1bjdFXhc8lKTLoq+RbwFM8M+orcMS9xrcqLmDGOxJcXpKizEeE5h6v/GKwCZV02FmhaA7OlNjoq072jZpQ==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.EventLog": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "Eck9GpCCpvZ3f6L7IUlN+mPtRVefnf7PsiIG5vi61QawPtLNCEAv2TPD/M3SojcU0PFaef+BxiVGPOShFHtDog==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11",
-          "System.Diagnostics.EventLog": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Logging.EventSource": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "hs6QWECLLohi2VKqUvSGRUvrg7eXR1DqKL95Jrtz3cdD2g2nBA+yJPdRQLZ7SLmnTZWycxfMDK2s0ho+rfst5w==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Logging": "10.0.11",
-          "Microsoft.Extensions.Logging.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Options": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "eY1GAKcTfD2maP27J84X9IovT3yjHJ2dVDzPmDg6/XqYvt3jMzJhtfQCLjG9pVsZGAd+8DQ2QrjaDcs2+VQLGw==",
-        "dependencies": {
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Options.ConfigurationExtensions": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "syEhXQ/sEaSBFaqzlp9gDGHX/nk6gkQkh1sIUpBO1mlBj3Phu1rmb4ML1uCiyPW9N6Kxfxv3y5FGObC+bV01Qw==",
-        "dependencies": {
-          "Microsoft.Extensions.Configuration.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Configuration.Binder": "10.0.11",
-          "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.11",
-          "Microsoft.Extensions.Options": "10.0.11",
-          "Microsoft.Extensions.Primitives": "10.0.11"
-        }
-      },
-      "Microsoft.Extensions.Primitives": {
-        "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "SXcz+kF+4Oo9b1+55zntpJFYfwb1jw66ioxptyNOOTDc8g2FHnBFWjZpsWfCvZIhzr0x+4e2trVTs4OKwQfBtw=="
-      },
       "Microsoft.Testing.Extensions.Telemetry": {
         "type": "Transitive",
         "resolved": "2.3.3",
@@ -374,10 +92,10 @@
         "resolved": "5.0.0",
         "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg=="
       },
-      "System.Diagnostics.EventLog": {
+      "Npgsql": {
         "type": "Transitive",
-        "resolved": "10.0.11",
-        "contentHash": "QTXEoQBzz00SFWbo7nAg1Ogd4f99lwqcO9uAJ7MYSLEUR28f6As32QktrqG2Fr9cfAfd1GjLyGYspE7Ipj7P6w=="
+        "resolved": "10.0.3",
+        "contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
       },
       "System.Security.AccessControl": {
         "type": "Transitive",
@@ -445,7 +163,8 @@
       "progmaweb.api": {
         "type": "Project",
         "dependencies": {
-          "Microsoft.AspNetCore.Authentication.Google": "[10.0.11, )"
+          "Microsoft.AspNetCore.Authentication.Google": "[10.0.11, )",
+          "Npgsql": "[10.0.3, )"
         }
       }
     }
diff --git a/apps/api/Accounts/AccountSchema.cs b/apps/api/Accounts/AccountSchema.cs
new file mode 100644
index 0000000..3fc3707
--- /dev/null
+++ b/apps/api/Accounts/AccountSchema.cs
@@ -0,0 +1,133 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Npgsql;
+
+namespace Progmasoft.Progmaweb.Api.Accounts;
+
+/// <summary>The tables of <see cref="PostgresAccountStore"/> and the steps that bring a database to them.</summary>
+/// <remarks>
+/// <para>
+/// The schema is a list of numbered steps. A database records the steps it has taken in
+/// <c>account_schema_versions</c>, and <see cref="ApplyAsync"/> takes the ones that are missing, in order, in one
+/// transaction. A step is never edited after it has been released; a change to the tables is a new step.
+/// </para>
+/// <para>
+/// The tables are created in the schema the connection selects, without a schema name in the statements, so the
+/// connection string decides where they live.
+/// </para>
+/// </remarks>
+internal static class AccountSchema
+{
+    /// <summary>Key of the advisory lock that lets one process at a time change the schema.</summary>
+    /// <remarks>The value is arbitrary and fixed; it only has to differ from the keys of other applications.</remarks>
+    private const long MigrationLockKey = 0x50726F676D6157;
+
+    /// <summary>The steps, in order. The version of a step is its position, counted from one.</summary>
+    private static readonly string[] Steps =
+    [
+        // 1: accounts and sessions.
+        //
+        // The three uniqueness rules of the store are the unique constraints below. A unique constraint ignores
+        // rows whose column is null, which is the rule for google_subject: many password accounts, each without a
+        // Google identity. A session is removed with its account, and the index on expires_at is what the removal
+        // of expired sessions scans.
+        """
+        CREATE TABLE accounts (
+            id                      uuid        PRIMARY KEY,
+            account_name            text        NOT NULL,
+            normalized_account_name text        NOT NULL CONSTRAINT accounts_normalized_account_name_key UNIQUE,
+            email                   text        NOT NULL,
+            normalized_email        text        NOT NULL CONSTRAINT accounts_normalized_email_key UNIQUE,
+            google_subject          text        CONSTRAINT accounts_google_subject_key UNIQUE,
+            password_hash           text,
+            created_at              timestamptz NOT NULL
+        );
+
+        CREATE TABLE sessions (
+            token_digest bytea       PRIMARY KEY,
+            account_id   uuid        NOT NULL REFERENCES accounts (id) ON DELETE CASCADE,
+            created_at   timestamptz NOT NULL,
+            expires_at   timestamptz NOT NULL
+        );
+
+        CREATE INDEX sessions_expires_at_idx ON sessions (expires_at);
+        CREATE INDEX sessions_account_id_idx ON sessions (account_id);
+        """
+    ];
+
+    /// <summary>The version a database has after every step.</summary>
+    public static int CurrentVersion => Steps.Length;
+
+    /// <summary>Takes the steps a database has not taken yet.</summary>
+    /// <remarks>
+    /// Processes that start together wait for one another on an advisory lock, so each step is taken once. A
+    /// database that is newer than this program is refused: its tables may no longer be what the store expects.
+    /// </remarks>
+    /// <param name="dataSource">Connections to the database.</param>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>The number of steps that were taken; zero when the database was current.</returns>
+    /// <exception cref="InvalidOperationException">The database has taken steps this program does not know.</exception>
+    public static async Task<int> ApplyAsync(NpgsqlDataSource dataSource, CancellationToken cancellationToken)
+    {
+        await using NpgsqlConnection connection = await dataSource.OpenConnectionAsync(cancellationToken);
+        await using NpgsqlTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
+
+        // The lock is released with the transaction, also when a step fails.
+        await ExecuteAsync(connection, transaction, $"SELECT pg_advisory_xact_lock({MigrationLockKey})", cancellationToken);
+        await ExecuteAsync(
+            connection,
+            transaction,
+            """
+            CREATE TABLE IF NOT EXISTS account_schema_versions (
+                version    integer     PRIMARY KEY,
+                applied_at timestamptz NOT NULL DEFAULT now()
+            )
+            """,
+            cancellationToken);
+
+        int version;
+        await using (NpgsqlCommand read = new(
+            "SELECT coalesce(max(version), 0) FROM account_schema_versions", connection, transaction))
+        {
+            version = (int)(await read.ExecuteScalarAsync(cancellationToken))!;
+        }
+
+        if (version > Steps.Length)
+        {
+            throw new InvalidOperationException(
+                $"The account database is at schema version {version}, and this program knows version {Steps.Length}. " +
+                "Run the release that created the database, or a newer one.");
+        }
+
+        int taken = 0;
+        for (int step = version; step < Steps.Length; step++)
+        {
+            await ExecuteAsync(connection, transaction, Steps[step], cancellationToken);
+            await using NpgsqlCommand record = new(
+                "INSERT INTO account_schema_versions (version) VALUES ($1)", connection, transaction);
+            record.Parameters.AddWithValue(step + 1);
+            await record.ExecuteNonQueryAsync(cancellationToken);
+            taken++;
+        }
+
+        await transaction.CommitAsync(cancellationToken);
+        return taken;
+    }
+
+    /// <summary>Runs statements that return nothing.</summary>
+    /// <param name="connection">The connection to run them on.</param>
+    /// <param name="transaction">The transaction they belong to.</param>
+    /// <param name="sql">The statements.</param>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>A task that completes when the statements have run.</returns>
+    private static async Task ExecuteAsync(
+        NpgsqlConnection connection,
+        NpgsqlTransaction transaction,
+        string sql,
+        CancellationToken cancellationToken)
+    {
+        await using NpgsqlCommand command = new(sql, connection, transaction);
+        await command.ExecuteNonQueryAsync(cancellationToken);
+    }
+}
diff --git a/apps/api/Accounts/AccountService.cs b/apps/api/Accounts/AccountService.cs
index cd3e711..7634948 100644
--- a/apps/api/Accounts/AccountService.cs
+++ b/apps/api/Accounts/AccountService.cs
@@ -76,7 +76,8 @@ internal sealed class AccountService(
             return (null, new Dictionary<string, string[]> { ["email"] = ["That email address is already registered."] });
         }
 
-        AuthenticatedAccount authentication = await sessions.CreateAsync(account, cancellationToken);
+        // The store returns the account as it keeps it, which is what every later read returns.
+        AuthenticatedAccount authentication = await sessions.CreateAsync(result.Account ?? account, cancellationToken);
         return (authentication, errors);
     }
 
@@ -200,7 +201,7 @@ internal sealed class AccountService(
                 : (await sessions.CreateAsync(concurrent, cancellationToken), GoogleAccountFailure.None);
         }
 
-        return (await sessions.CreateAsync(account, cancellationToken), GoogleAccountFailure.None);
+        return (await sessions.CreateAsync(result.Account ?? account, cancellationToken), GoogleAccountFailure.None);
     }
 
     /// <summary>Validates every field of a registration and collects the messages of the refused ones.</summary>
diff --git a/apps/api/Accounts/AccountStoreRegistration.cs b/apps/api/Accounts/AccountStoreRegistration.cs
new file mode 100644
index 0000000..14a77a6
--- /dev/null
+++ b/apps/api/Accounts/AccountStoreRegistration.cs
@@ -0,0 +1,253 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Npgsql;
+
+namespace Progmasoft.Progmaweb.Api.Accounts;
+
+/// <summary>Which <see cref="IAccountStore"/> a configuration selects.</summary>
+internal enum AccountStoreKind
+{
+    /// <summary><see cref="InMemoryAccountStore"/>: nothing survives a restart.</summary>
+    Memory,
+    /// <summary><see cref="PostgresAccountStore"/>: accounts and sessions survive a restart.</summary>
+    PostgreSql
+}
+
+/// <summary>Chooses the account store from the configuration and registers what belongs to it.</summary>
+/// <remarks>
+/// <para>
+/// <c>ConnectionStrings:Accounts</c> names the PostgreSQL database. <c>Accounts:Store</c> may name the store
+/// outright, as <c>PostgreSQL</c> or <c>Memory</c>. Without it, a connection string selects PostgreSQL.
+/// </para>
+/// <para>
+/// A production service that is given neither does not start. Keeping accounts in memory there has to be asked for
+/// with <c>Accounts:Store=Memory</c>, because a service that quietly forgets every account at each restart is the
+/// failure this store exists to prevent. Outside production the default without a connection string is memory.
+/// </para>
+/// </remarks>
+internal static class AccountStoreRegistration
+{
+    /// <summary>Writes the warning of <see cref="WarnThatAccountsAreInMemory"/>.</summary>
+    private static readonly Action<ILogger, Exception?> InMemoryWarning = LoggerMessage.Define(
+        LogLevel.Warning,
+        new EventId(1, "AccountsInMemory"),
+        "Accounts are kept in memory: every account and session is lost when this service stops.");
+
+    /// <summary>Name of the connection string of the account database.</summary>
+    public const string ConnectionStringName = "Accounts";
+
+    /// <summary>Configuration key that names the store outright.</summary>
+    public const string StoreKey = "Accounts:Store";
+
+    /// <summary>Decides which store a configuration selects.</summary>
+    /// <param name="configuration">The configuration of the service.</param>
+    /// <param name="isProduction">Whether the service runs in the production environment.</param>
+    /// <returns>The selected store.</returns>
+    /// <exception cref="InvalidOperationException">
+    /// The store is named with an unknown word, PostgreSQL is named without a connection string, memory is named
+    /// with one, or a production service is given neither.
+    /// </exception>
+    public static AccountStoreKind Select(IConfiguration configuration, bool isProduction)
+    {
+        string? named = configuration[StoreKey];
+        bool hasConnectionString = !string.IsNullOrWhiteSpace(configuration.GetConnectionString(ConnectionStringName));
+
+        if (string.IsNullOrWhiteSpace(named))
+        {
+            if (hasConnectionString)
+            {
+                return AccountStoreKind.PostgreSql;
+            }
+
+            return isProduction
+                ? throw new InvalidOperationException(
+                    $"No account database is configured. Set ConnectionStrings:{ConnectionStringName} to the " +
+                    $"PostgreSQL database of the accounts, or set {StoreKey}=Memory to accept that every account " +
+                    "and session is lost when the service restarts.")
+                : AccountStoreKind.Memory;
+        }
+
+        if (string.Equals(named, "PostgreSQL", StringComparison.OrdinalIgnoreCase))
+        {
+            return hasConnectionString
+                ? AccountStoreKind.PostgreSql
+                : throw new InvalidOperationException(
+                    $"{StoreKey} is PostgreSQL, and ConnectionStrings:{ConnectionStringName} is not set.");
+        }
+
+        if (string.Equals(named, "Memory", StringComparison.OrdinalIgnoreCase))
+        {
+            // Both together would leave a configured database unused without anyone noticing.
+            return hasConnectionString
+                ? throw new InvalidOperationException(
+                    $"{StoreKey} is Memory, and ConnectionStrings:{ConnectionStringName} is set. Remove one of them.")
+                : AccountStoreKind.Memory;
+        }
+
+        throw new InvalidOperationException($"{StoreKey} is '{named}'. It must be PostgreSQL or Memory.");
+    }
+
+    /// <summary>Registers the selected store, and for PostgreSQL its schema step, health check and connections.</summary>
+    /// <param name="services">The services of the application.</param>
+    /// <param name="configuration">The configuration of the service.</param>
+    /// <param name="isProduction">Whether the service runs in the production environment.</param>
+    /// <returns>The selected store, so that the caller can report it.</returns>
+    public static AccountStoreKind AddAccountStore(
+        this IServiceCollection services,
+        IConfiguration configuration,
+        bool isProduction)
+    {
+        AccountStoreKind kind = Select(configuration, isProduction);
+        IHealthChecksBuilder health = services.AddHealthChecks();
+        if (kind is AccountStoreKind.Memory)
+        {
+            services.AddSingleton<IAccountStore, InMemoryAccountStore>();
+        }
+        else
+        {
+            string connectionString = configuration.GetConnectionString(ConnectionStringName)!;
+            // The data source owns the connection pool; the container disposes it when the service stops.
+            services.AddSingleton(_ => NpgsqlDataSource.Create(connectionString));
+            services.AddSingleton<IAccountStore, PostgresAccountStore>();
+            // Registered before the session cleanup, so the tables exist before anything reads them.
+            services.AddHostedService<AccountSchemaInitializer>();
+            health.AddCheck<AccountDatabaseHealthCheck>("account-database");
+        }
+
+        services.AddHostedService<ExpiredSessionCleanup>();
+        return kind;
+    }
+
+    /// <summary>Writes to the log that this service forgets its accounts when it stops.</summary>
+    /// <param name="logger">The log of the service.</param>
+    public static void WarnThatAccountsAreInMemory(ILogger logger) => InMemoryWarning(logger, null);
+}
+
+/// <summary>Brings the account database to the current schema before the service accepts requests.</summary>
+/// <remarks>
+/// A database that cannot be reached, or that is newer than the program, stops the start of the service. A service
+/// that started without its tables would answer every account request with an error instead.
+/// </remarks>
+/// <param name="dataSource">Connections to the account database.</param>
+/// <param name="logger">Receives what was done.</param>
+internal sealed class AccountSchemaInitializer(
+    NpgsqlDataSource dataSource,
+    ILogger<AccountSchemaInitializer> logger) : IHostedService
+{
+    /// <summary>Writes the schema version and the number of steps taken at this start.</summary>
+    private static readonly Action<ILogger, int, int, Exception?> SchemaReport = LoggerMessage.Define<int, int>(
+        LogLevel.Information,
+        new EventId(2, "AccountSchema"),
+        "The account database is at schema version {Version}; {Taken} step(s) were taken at this start.");
+
+    /// <inheritdoc/>
+    public async Task StartAsync(CancellationToken cancellationToken)
+    {
+        int taken = await AccountSchema.ApplyAsync(dataSource, cancellationToken);
+        SchemaReport(logger, AccountSchema.CurrentVersion, taken, null);
+    }
+
+    /// <inheritdoc/>
+    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+}
+
+/// <summary>Reports whether the account database answers.</summary>
+/// <param name="dataSource">Connections to the account database.</param>
+internal sealed class AccountDatabaseHealthCheck(NpgsqlDataSource dataSource) : IHealthCheck
+{
+    /// <inheritdoc/>
+    public async Task<HealthCheckResult> CheckHealthAsync(
+        HealthCheckContext context,
+        CancellationToken cancellationToken = default)
+    {
+        try
+        {
+            await using NpgsqlCommand command = dataSource.CreateCommand("SELECT 1");
+            await command.ExecuteScalarAsync(cancellationToken);
+            return HealthCheckResult.Healthy();
+        }
+        catch (Exception exception) when (exception is NpgsqlException or TimeoutException or IOException)
+        {
+            // The description is written to the log of the service, never to the response of /health.
+            return HealthCheckResult.Unhealthy("The account database does not answer.", exception);
+        }
+    }
+}
+
+/// <summary>Removes sessions that have expired, once at the start and then once an hour.</summary>
+/// <remarks>
+/// An expired session is already refused when its token is presented, and removed then. A token that is never
+/// presented again would otherwise keep its row for ever; this removes those. A removal that fails is logged and
+/// tried again at the next hour, because the service works without it.
+/// </remarks>
+/// <param name="store">The store whose sessions are removed.</param>
+/// <param name="timeProvider">Clock that decides what has expired and paces the removals.</param>
+/// <param name="logger">Receives what was done.</param>
+internal sealed class ExpiredSessionCleanup(
+    IAccountStore store,
+    TimeProvider timeProvider,
+    ILogger<ExpiredSessionCleanup> logger) : BackgroundService
+{
+    /// <summary>Writes how many expired sessions a removal took.</summary>
+    private static readonly Action<ILogger, int, Exception?> RemovedReport = LoggerMessage.Define<int>(
+        LogLevel.Information,
+        new EventId(3, "ExpiredSessionsRemoved"),
+        "Removed {Count} expired session(s).");
+
+    /// <summary>Writes that a removal failed, with its cause.</summary>
+    private static readonly Action<ILogger, Exception?> FailureReport = LoggerMessage.Define(
+        LogLevel.Warning,
+        new EventId(4, "ExpiredSessionsNotRemoved"),
+        "Expired sessions could not be removed; the next hour tries again.");
+
+    /// <summary>Time between two removals.</summary>
+    internal static readonly TimeSpan Interval = TimeSpan.FromHours(1);
+
+    /// <inheritdoc/>
+    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+    {
+        using PeriodicTimer timer = new(Interval, timeProvider);
+        do
+        {
+            await RemoveOnceAsync(stoppingToken);
+        }
+        while (await WaitAsync(timer, stoppingToken));
+    }
+
+    /// <summary>Removes what has expired by now.</summary>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>A task that completes when the removal has run or has failed.</returns>
+    internal async Task RemoveOnceAsync(CancellationToken cancellationToken)
+    {
+        try
+        {
+            int removed = await store.RemoveExpiredSessionsAsync(timeProvider.GetUtcNow(), cancellationToken);
+            if (removed != 0)
+            {
+                RemovedReport(logger, removed, null);
+            }
+        }
+        catch (Exception exception) when (exception is not OperationCanceledException)
+        {
+            FailureReport(logger, exception);
+        }
+    }
+
+    /// <summary>Waits for the next tick; stopping the service ends the wait without an error.</summary>
+    /// <param name="timer">The timer that paces the removals.</param>
+    /// <param name="stoppingToken">Signals that the service stops.</param>
+    /// <returns><see langword="true"/> at a tick, <see langword="false"/> when the service stops.</returns>
+    private static async Task<bool> WaitAsync(PeriodicTimer timer, CancellationToken stoppingToken)
+    {
+        try
+        {
+            return await timer.WaitForNextTickAsync(stoppingToken);
+        }
+        catch (OperationCanceledException)
+        {
+            return false;
+        }
+    }
+}
diff --git a/apps/api/Accounts/IAccountStore.cs b/apps/api/Accounts/IAccountStore.cs
index cef8bee..efb7c5b 100644
--- a/apps/api/Accounts/IAccountStore.cs
+++ b/apps/api/Accounts/IAccountStore.cs
@@ -6,7 +6,8 @@ namespace Progmasoft.Progmaweb.Api.Accounts;
 /// <summary>Persistence of accounts and sessions.</summary>
 /// <remarks>
 /// The store owns the uniqueness rules: account name, email address and Google identity are each unique, and a
-/// creation that would break one of them is refused atomically. It offers no enumeration and no bulk deletion.
+/// creation that would break one of them is refused atomically. It offers no enumeration of accounts and no way to
+/// delete one; the only removal in bulk is that of sessions that have already expired.
 /// </remarks>
 internal interface IAccountStore
 {
@@ -45,5 +46,11 @@ internal interface IAccountStore
     /// <param name="cancellationToken">Cancels the operation.</param>
     /// <returns>A task that completes when the session is gone.</returns>
     ValueTask RevokeSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken);
+    /// <summary>Removes every session that has expired.</summary>
+    /// <remarks>A session has expired when its expiry is not later than <paramref name="now"/>.</remarks>
+    /// <param name="now">The current moment, in UTC.</param>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>The number of sessions that were removed.</returns>
+    ValueTask<int> RemoveExpiredSessionsAsync(DateTimeOffset now, CancellationToken cancellationToken);
 }
 
diff --git a/apps/api/Accounts/InMemoryAccountStore.cs b/apps/api/Accounts/InMemoryAccountStore.cs
index 7a6930f..8606443 100644
--- a/apps/api/Accounts/InMemoryAccountStore.cs
+++ b/apps/api/Accounts/InMemoryAccountStore.cs
@@ -3,12 +3,11 @@
 
 namespace Progmasoft.Progmaweb.Api.Accounts;
 
-// This development store models the uniqueness and session semantics required by the future PostgreSQL implementation.
-// It deliberately exposes no enumeration or bulk-delete surface to public endpoints.
 /// <summary>An <see cref="IAccountStore"/> that keeps everything in the memory of the process.</summary>
 /// <remarks>
-/// It implements the uniqueness and session rules a durable store must keep, under one lock. Nothing survives a
-/// restart of the service: every account and every session is lost when the process stops.
+/// It keeps the uniqueness and session rules of <see cref="PostgresAccountStore"/> under one lock, for development
+/// and for tests that need no database. Nothing survives a restart of the service: every account and every session
+/// is lost when the process stops.
 /// </remarks>
 internal sealed class InMemoryAccountStore : IAccountStore
 {
@@ -99,6 +98,12 @@ internal sealed class InMemoryAccountStore : IAccountStore
         cancellationToken.ThrowIfCancellationRequested();
         lock (gate)
         {
+            // The durable store refuses a session of an account that does not exist; so does this one.
+            if (!accountsById.ContainsKey(session.AccountId))
+            {
+                throw new InvalidOperationException("A session refers to an account that is not stored.");
+            }
+
             sessionsByDigest[Convert.ToHexString(session.TokenDigest)] = session;
             return ValueTask.CompletedTask;
         }
@@ -125,5 +130,20 @@ internal sealed class InMemoryAccountStore : IAccountStore
             return ValueTask.CompletedTask;
         }
     }
+
+    /// <inheritdoc/>
+    public ValueTask<int> RemoveExpiredSessionsAsync(DateTimeOffset now, CancellationToken cancellationToken)
+    {
+        cancellationToken.ThrowIfCancellationRequested();
+        lock (gate)
+        {
+            string[] expired = [.. sessionsByDigest.Where(entry => entry.Value.ExpiresAt <= now).Select(entry => entry.Key)];
+            foreach (string digest in expired)
+            {
+                sessionsByDigest.Remove(digest);
+            }
+            return ValueTask.FromResult(expired.Length);
+        }
+    }
 }
 
diff --git a/apps/api/Accounts/PostgresAccountStore.cs b/apps/api/Accounts/PostgresAccountStore.cs
new file mode 100644
index 0000000..a0e3444
--- /dev/null
+++ b/apps/api/Accounts/PostgresAccountStore.cs
@@ -0,0 +1,200 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Npgsql;
+
+namespace Progmasoft.Progmaweb.Api.Accounts;
+
+/// <summary>An <see cref="IAccountStore"/> that keeps accounts and sessions in PostgreSQL.</summary>
+/// <remarks>
+/// <para>
+/// The uniqueness rules are unique indexes of the <c>accounts</c> table, so two requests that race for one name,
+/// address or Google identity are decided by the database: one row is stored and the other request is refused. A
+/// session row refers to its account, and the database refuses a session of an account that does not exist.
+/// </para>
+/// <para>
+/// PostgreSQL keeps a timestamp to the microsecond. A moment is cut to that precision before it is stored, and the
+/// store returns what it stored, so a value read later equals the value returned when it was written.
+/// </para>
+/// </remarks>
+/// <param name="dataSource">Connections to the database that holds the tables of <see cref="AccountSchema"/>.</param>
+internal sealed class PostgresAccountStore(NpgsqlDataSource dataSource) : IAccountStore
+{
+    /// <summary>How often a creation is tried again when it was refused and no rule that refuses it is found.</summary>
+    private const int CreateAttempts = 3;
+
+    /// <summary>The columns of an account, in the order <see cref="ReadAccount"/> reads them.</summary>
+    private const string AccountColumns =
+        "id, account_name, normalized_account_name, email, normalized_email, google_subject, password_hash, created_at";
+
+    /// <inheritdoc/>
+    public async ValueTask<CreateAccountResult> CreateAsync(AccountRecord account, CancellationToken cancellationToken)
+    {
+        AccountRecord stored = account with { CreatedAt = ToStoredPrecision(account.CreatedAt) };
+
+        for (int attempt = 0; attempt < CreateAttempts; attempt++)
+        {
+            // A row that breaks a unique index is skipped instead of raising an error, so that a taken name is an
+            // ordinary answer and the transaction log holds no failed statement for it.
+            await using (NpgsqlCommand insert = dataSource.CreateCommand(
+                $"INSERT INTO accounts ({AccountColumns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT DO NOTHING"))
+            {
+                insert.Parameters.AddWithValue(stored.Id);
+                insert.Parameters.AddWithValue(stored.AccountName);
+                insert.Parameters.AddWithValue(stored.NormalizedAccountName);
+                insert.Parameters.AddWithValue(stored.Email);
+                insert.Parameters.AddWithValue(stored.NormalizedEmail);
+                insert.Parameters.AddWithValue(NullableText(stored.GoogleSubject));
+                insert.Parameters.AddWithValue(NullableText(stored.PasswordHash));
+                insert.Parameters.AddWithValue(stored.CreatedAt);
+                if (await insert.ExecuteNonQueryAsync(cancellationToken) == 1)
+                {
+                    return CreateAccountResult.Created(stored);
+                }
+            }
+
+            // The rules are reported in one fixed order, the order of the in-memory store, whichever index the
+            // database happened to check first.
+            await using NpgsqlCommand taken = dataSource.CreateCommand(
+                """
+                SELECT EXISTS (SELECT 1 FROM accounts WHERE google_subject = $1),
+                       EXISTS (SELECT 1 FROM accounts WHERE normalized_account_name = $2),
+                       EXISTS (SELECT 1 FROM accounts WHERE normalized_email = $3)
+                """);
+            taken.Parameters.AddWithValue(NullableText(stored.GoogleSubject));
+            taken.Parameters.AddWithValue(stored.NormalizedAccountName);
+            taken.Parameters.AddWithValue(stored.NormalizedEmail);
+            await using NpgsqlDataReader reader = await taken.ExecuteReaderAsync(cancellationToken);
+            await reader.ReadAsync(cancellationToken);
+            if (reader.GetBoolean(0))
+            {
+                return CreateAccountResult.GoogleSubjectUnavailable();
+            }
+
+            if (reader.GetBoolean(1))
+            {
+                return CreateAccountResult.AccountNameUnavailable();
+            }
+
+            if (reader.GetBoolean(2))
+            {
+                return CreateAccountResult.EmailUnavailable();
+            }
+        }
+
+        // Accounts are never deleted, so a refused row always has a row that refuses it. Reaching this line means
+        // the identifier itself was taken, which a random identifier does not do.
+        throw new InvalidOperationException("The account store refused an account without a rule that explains it.");
+    }
+
+    /// <inheritdoc/>
+    public ValueTask<AccountRecord?> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) =>
+        FindAccountAsync("normalized_email", normalizedEmail, cancellationToken);
+
+    /// <inheritdoc/>
+    public ValueTask<AccountRecord?> FindByGoogleSubjectAsync(
+        string googleSubject,
+        CancellationToken cancellationToken) =>
+        FindAccountAsync("google_subject", googleSubject, cancellationToken);
+
+    /// <inheritdoc/>
+    public ValueTask<AccountRecord?> FindByIdAsync(Guid id, CancellationToken cancellationToken) =>
+        FindAccountAsync("id", id, cancellationToken);
+
+    /// <inheritdoc/>
+    public async ValueTask StoreSessionAsync(SessionRecord session, CancellationToken cancellationToken)
+    {
+        await using NpgsqlCommand command = dataSource.CreateCommand(
+            """
+            INSERT INTO sessions (token_digest, account_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
+            ON CONFLICT (token_digest) DO UPDATE
+                SET account_id = EXCLUDED.account_id, created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at
+            """);
+        command.Parameters.AddWithValue(session.TokenDigest);
+        command.Parameters.AddWithValue(session.AccountId);
+        command.Parameters.AddWithValue(ToStoredPrecision(session.CreatedAt));
+        command.Parameters.AddWithValue(ToStoredPrecision(session.ExpiresAt));
+        await command.ExecuteNonQueryAsync(cancellationToken);
+    }
+
+    /// <inheritdoc/>
+    public async ValueTask<SessionRecord?> FindSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken)
+    {
+        await using NpgsqlCommand command = dataSource.CreateCommand(
+            "SELECT token_digest, account_id, created_at, expires_at FROM sessions WHERE token_digest = $1");
+        command.Parameters.AddWithValue(tokenDigest);
+        await using NpgsqlDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
+        if (!await reader.ReadAsync(cancellationToken))
+        {
+            return null;
+        }
+
+        return new SessionRecord(
+            reader.GetFieldValue<byte[]>(0),
+            reader.GetGuid(1),
+            reader.GetFieldValue<DateTimeOffset>(2),
+            reader.GetFieldValue<DateTimeOffset>(3));
+    }
+
+    /// <inheritdoc/>
+    public async ValueTask RevokeSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken)
+    {
+        await using NpgsqlCommand command = dataSource.CreateCommand("DELETE FROM sessions WHERE token_digest = $1");
+        command.Parameters.AddWithValue(tokenDigest);
+        await command.ExecuteNonQueryAsync(cancellationToken);
+    }
+
+    /// <inheritdoc/>
+    public async ValueTask<int> RemoveExpiredSessionsAsync(DateTimeOffset now, CancellationToken cancellationToken)
+    {
+        await using NpgsqlCommand command = dataSource.CreateCommand("DELETE FROM sessions WHERE expires_at <= $1");
+        command.Parameters.AddWithValue(now.ToUniversalTime());
+        return await command.ExecuteNonQueryAsync(cancellationToken);
+    }
+
+    /// <summary>Finds the one account whose column has a value.</summary>
+    /// <typeparam name="TKey">Type of the value.</typeparam>
+    /// <param name="column">Name of a column with a unique index. It is written into the statement.</param>
+    /// <param name="value">The value to look for.</param>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>The account, or <see langword="null"/> when no account has the value.</returns>
+    private async ValueTask<AccountRecord?> FindAccountAsync<TKey>(
+        string column,
+        TKey value,
+        CancellationToken cancellationToken)
+        where TKey : notnull
+    {
+        await using NpgsqlCommand command = dataSource.CreateCommand(
+            $"SELECT {AccountColumns} FROM accounts WHERE {column} = $1");
+        command.Parameters.AddWithValue(value);
+        await using NpgsqlDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
+        return await reader.ReadAsync(cancellationToken) ? ReadAccount(reader) : null;
+    }
+
+    /// <summary>Reads the account of the current row; the columns are <see cref="AccountColumns"/>.</summary>
+    /// <param name="reader">A reader positioned on a row.</param>
+    /// <returns>The account of the row.</returns>
+    private static AccountRecord ReadAccount(NpgsqlDataReader reader) => new(
+        reader.GetGuid(0),
+        reader.GetString(1),
+        reader.GetString(2),
+        reader.GetString(3),
+        reader.GetString(4),
+        reader.IsDBNull(5) ? null : reader.GetString(5),
+        reader.IsDBNull(6) ? null : reader.GetString(6),
+        reader.GetFieldValue<DateTimeOffset>(7));
+
+    /// <summary>Converts an optional text to a parameter value.</summary>
+    /// <param name="value">The text, or <see langword="null"/>.</param>
+    /// <returns>The text, or the database null.</returns>
+    private static object NullableText(string? value) => value is null ? DBNull.Value : value;
+
+    /// <summary>Cuts a moment to the microsecond PostgreSQL keeps, in UTC.</summary>
+    /// <param name="moment">The moment to store.</param>
+    /// <returns>The moment as the database will return it.</returns>
+    internal static DateTimeOffset ToStoredPrecision(DateTimeOffset moment)
+    {
+        DateTimeOffset utc = moment.ToUniversalTime();
+        return utc.AddTicks(-(utc.Ticks % (TimeSpan.TicksPerMillisecond / 1000)));
+    }
+}
diff --git a/apps/api/Progmaweb.Api.csproj b/apps/api/Progmaweb.Api.csproj
index 926e696..29086cb 100644
--- a/apps/api/Progmaweb.Api.csproj
+++ b/apps/api/Progmaweb.Api.csproj
@@ -13,6 +13,7 @@
   </PropertyGroup>
   <ItemGroup>
     <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.11" />
+    <PackageReference Include="Npgsql" Version="10.0.3" />
   </ItemGroup>
   <ItemGroup>
     <InternalsVisibleTo Include="Progmaweb.Api.Tests" />
diff --git a/apps/api/Program.cs b/apps/api/Program.cs
index b5c8708..fd6e97b 100644
--- a/apps/api/Program.cs
+++ b/apps/api/Program.cs
@@ -13,7 +13,9 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
 builder.Services.Configure<AccountSessionOptions>(builder.Configuration.GetSection(AccountSessionOptions.SectionName));
 builder.Services.AddSingleton(TimeProvider.System);
-builder.Services.AddSingleton<IAccountStore, InMemoryAccountStore>();
+AccountStoreKind accountStore = builder.Services.AddAccountStore(
+    builder.Configuration,
+    builder.Environment.IsProduction());
 builder.Services.AddSingleton<AccountService>();
 builder.Services.AddSingleton<SessionService>();
 AuthenticationBuilder authentication = builder.Services
@@ -69,6 +71,11 @@ builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize =
 
 WebApplication app = builder.Build();
 
+if (accountStore is AccountStoreKind.Memory)
+{
+    AccountStoreRegistration.WarnThatAccountsAreInMemory(app.Logger);
+}
+
 app.UseForwardedHeaders();
 if (!app.Environment.IsDevelopment())
 {
diff --git a/apps/api/packages.lock.json b/apps/api/packages.lock.json
index b7d7ff4..70c33f8 100644
--- a/apps/api/packages.lock.json
+++ b/apps/api/packages.lock.json
@@ -7,6 +7,12 @@
         "requested": "[10.0.11, )",
         "resolved": "10.0.11",
         "contentHash": "v/OZld8HxGa5hudLWiChuCf5asMrE36n19sR1RK5cC65SGJoYvQAcwnz3yoAOLDSw90PYc3hgFCh1FW83sakUg=="
+      },
+      "Npgsql": {
+        "type": "Direct",
+        "requested": "[10.0.3, )",
+        "resolved": "10.0.3",
+        "contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
       }
     }
   }
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ef5a427..cb4b20f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -90,7 +90,9 @@ step.
   parameter and the `Accept-Language` header. Each is validated against the list of published locales.
 - **Nginx and Next.js to the API.** The API trusts forwarded headers only from loopback and reads one proxy hop. A
   caller that reached the API directly could otherwise forge the client address that the rate limiter uses.
-- **API to its store.** The store keeps password hashes and session digests, never passwords or session tokens.
+- **API to its store.** The store is a PostgreSQL database on the same host, reached through its Unix socket as the
+  operating system user of the service, without a password. It keeps password hashes and session digests, never
+  passwords or session tokens.
 - **What the browser never receives.** Password hashes, session digests, deployment secrets and internal addresses.
 
 The API has no bulk-delete, reset-all or seed-password endpoint. Maintenance of production accounts is an operations
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 022af77..85c4638 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -18,7 +18,7 @@
 ```text
 apps/web          Next.js application: pages, components, localization, host routing
 apps/api          ASP.NET Core account API
-apps/api-tests    xUnit tests of the API, run against the application in memory
+apps/api-tests    xUnit tests of the API, run against the application in memory and against PostgreSQL
 docs              this documentation and the DocFX project in docs/api
 ops               Nginx, systemd and mail configuration with their runbooks
 ```
@@ -49,7 +49,14 @@ Open the three surfaces through their development host names:
 | `http://account.localhost:3000/` | account pages |
 | `http://viget.localhost:3000/` | ViGet catalogs |
 
-Accounts created locally live in the memory of the API process and are gone when it stops.
+Accounts created locally live in the memory of the API process and are gone when it stops. To keep them, point the
+API at a PostgreSQL database before it starts; it creates its tables itself:
+
+```text
+ConnectionStrings__Accounts=Host=localhost;Database=progmaweb_accounts;Username=<role>
+```
+
+Production always uses PostgreSQL; see [Operations](../ops/README.md).
 
 Sign-in with Google is optional locally. It needs the identifier and secret of a Google OAuth client in
 `Authentication__Google__ClientId` and `Authentication__Google__ClientSecret`, set in the environment before the API
@@ -84,6 +91,11 @@ themes, a narrow window, and keyboard focus.
 - **Frontend** (`apps/web/tests`): the list of published locales, the shape of every message tree, language
   negotiation, cookie attributes, text direction and page metadata. The tests import the TypeScript sources directly
   and do not start a server.
+- **Account store** (`apps/api-tests`): one set of rules, `AccountStoreContractTests`, run against the in-memory
+  store and against PostgreSQL, so the two cannot drift apart; the schema steps; and an account with its session
+  surviving a restart of the service. The PostgreSQL tests need the connection string of a database whose user may
+  create schemas in `PROGMAWEB_TEST_POSTGRES`; each test works in a schema of its own and removes it. Without the
+  variable they are skipped locally. CI starts PostgreSQL for them and fails when the variable is missing.
 - **API** (`apps/api-tests`): the endpoints through an in-memory application, including validation, duplicate names
   and addresses, session cookies, the Google flow and security headers; and the account service on its own. The rate
   limit has no automated test.
diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md
index 6d09e7d..648a3df 100644
--- a/docs/LIMITATIONS.md
+++ b/docs/LIMITATIONS.md
@@ -6,17 +6,22 @@
 This page lists what Progmaweb does not do yet, so that nobody has to discover it in production. Each entry says what
 is missing, what follows from it, and what would close it.
 
-## Accounts are kept in memory
+## The account database has no backup yet
 
-The account API registers `InMemoryAccountStore` as its only store. Accounts and sessions live in the memory of the
-API process.
+Accounts and sessions are kept in PostgreSQL; see [Operations](../ops/README.md). Restarting or redeploying the API no
+longer loses them. Nothing copies the database anywhere else yet.
 
-- **Consequence.** Every restart of the API service deletes all accounts and signs everyone out. A deployment that
-  restarts the API has this effect.
-- **In operations.** Do not restart the API unless its code or configuration changed. A release that changes only the
-  frontend should restart only the frontend service; see [Operations](../ops/README.md).
-- **What closes it.** A durable implementation of `IAccountStore`. The interface already states the uniqueness and
-  session rules such a store must keep.
+- **Consequence.** Losing the disk of the host, or dropping the database by mistake, loses every account.
+- **What closes it.** A scheduled `pg_dump` of the account database to storage outside the host, and a restore that
+  has been tried once.
+
+## Accounts cannot be deleted
+
+The store has no operation that removes an account, and the API has no endpoint for it.
+
+- **Consequence.** A request to erase an account has to be carried out by hand in the database, by its operator.
+- **What closes it.** A deletion operation in the store with an endpoint or an operator command, and a decision about
+  what happens to the account name afterwards.
 
 ## Email addresses are not verified
 
diff --git a/ops/README.md b/ops/README.md
index 646d981..886b496 100644
--- a/ops/README.md
+++ b/ops/README.md
@@ -39,18 +39,51 @@ avoids depending on an apphost inode copied from a build machine retaining an ex
    sitemaps, `/api/v1/status`, registration validation, and the existing Visual X# host.
 6. On failure, restore the previous `current` target and restart only the Progmaweb services.
 
-## Restarting the API deletes every account
+## Account database
 
-The account store is in memory; see [Known limitations](../docs/LIMITATIONS.md). Restarting `progmaweb-api` deletes
-all accounts and sessions. Until a durable store exists:
+The API keeps accounts and sessions in PostgreSQL. It reads the connection string from `ConnectionStrings__Accounts`
+in `/etc/progmaweb/account.env`, the file the service unit already loads.
 
-- When a release changes only `apps/web`, copy the `api` directory of the running release into the new release,
-  confirm that the two directories are identical, switch `current`, and restart **only** `progmaweb-web`. The running
-  API process keeps serving from the files it already opened.
-- When a release changes `apps/api`, restarting the API is unavoidable. Say so before deploying, because every user
-  has to register again.
+The connection uses the Unix socket of the local server and peer authentication: PostgreSQL accepts the operating
+system user `progmaweb` as the database role `progmaweb`. No password exists, so none can leak:
 
-Step 4 of the activation contract restarts both services; apply it to the API only in the second case.
+```text
+ConnectionStrings__Accounts=Host=/var/run/postgresql;Database=progmaweb_accounts;Username=progmaweb
+```
+
+Prepare the database once, before the first release that needs it:
+
+1. Create the role and its database as the `postgres` user: a role `progmaweb` that may log in and nothing else, and
+   a database `progmaweb_accounts` owned by it. The role must not be a superuser and needs no rights in any other
+   database.
+2. Confirm that `pg_hba.conf` has a `local ... peer` line that covers the database. Do not add a TCP rule or a
+   password for this role.
+3. Add the line above to `/etc/progmaweb/account.env`. Keep the file `root:progmaweb` with mode `0640`.
+4. Check the connection as the service user before starting the service:
+   `runuser -u progmaweb -- psql -d progmaweb_accounts -c 'select current_user'`.
+
+The API creates and upgrades its own tables when it starts, in one transaction, and records the steps in
+`account_schema_versions`. It does not start when the database cannot be reached or when the database is newer than
+the release. `/health` on the loopback port answers 503 while the database does not answer.
+
+A production API without a connection string does not start. Keeping accounts in memory there has to be asked for
+with `Accounts__Store=Memory`, which loses every account at each restart; use it only for a host that must run
+without a database for a short time.
+
+The account database belongs to Progmaweb alone. Other services on the host have their own databases and roles; do
+not share a role or a database with them.
+
+### Releases and rollback
+
+- Restarting the API keeps every account and session. Step 4 of the activation contract applies to both services.
+- A release that adds a schema step upgrades the database at its first start. The previous release then refuses to
+  start, because the database is newer than it. Before activating such a release, take a dump with
+  `pg_dump --format=custom progmaweb_accounts`; rolling back means restoring that dump and then pointing `current`
+  at the previous release.
+- A release without a schema step rolls back as before: `current` points at the previous directory and the services
+  restart.
+
+There is no scheduled backup yet; see [Known limitations](../docs/LIMITATIONS.md).
 
 ## Lessons from past releases
 
diff --git a/ops/systemd/progmaweb-api.service b/ops/systemd/progmaweb-api.service
index a2b4fd8..daab684 100644
--- a/ops/systemd/progmaweb-api.service
+++ b/ops/systemd/progmaweb-api.service
@@ -3,8 +3,8 @@
 
 [Unit]
 Description=Progmaweb account API
-After=network-online.target
-Wants=network-online.target
+After=network-online.target postgresql.service
+Wants=network-online.target postgresql.service
 
 [Service]
 Type=exec
@@ -22,7 +22,8 @@ Restart=on-failure
 RestartSec=5s
 TimeoutStopSec=30s
 
-# The API currently has no writable application files. Runtime state belongs in external services, not in the release.
+# The API has no writable application files. Its state is in PostgreSQL, reached through the local Unix socket; the
+# connection string is in the environment file above.
 NoNewPrivileges=true
 PrivateTmp=true
 ProtectHome=true