← Pekka Ylenius

Leaving Cosmos DB: PostgreSQL jsonb and EF Core 10 as a Document Database

12 Oct 2026 · 10 min read · Originally published on Medium

In January I wrote about building full-text, vector and hybrid search on Azure Cosmos DB. This autumn I deleted the last line of Cosmos DB code from Eport, the booking, ticketing and membership platform I work on for sports venues. Everything now lives in a single PostgreSQL server on a Hetzner machine: the relational data that used to be in SQL Server, and the documents that used to be in Cosmos DB.

The stack is still .NET, but nothing in the request path depends on Microsoft’s cloud anymore. .NET runs in a Linux container, EF Core talks to Postgres through Npgsql, and the backups are a nightly pg_dump.

What surprised me most is how little we gave up. EF Core 10 can map a jsonb column as a complex type, so a LINQ filter on a field deep inside a document turns into a Postgres JSON operator. Here is how we got there, what we had to rebuild ourselves, and the things that bit us.

Where we started

Eport had two databases. Users, memberships, payments and events were relational and lived in SQL Server. Everything shaped like a document lived in Cosmos DB: support tickets and their messages, the knowledge base, CRM leads and pipelines, AI chat conversations, training plans, uploaded files, notes with embeddings for search. About twenty repositories sat on a shared Cosmos base class.

Every document carried the usual Cosmos system fields (id, the partition key pk, _etag, _ts, ttl) plus two of our own: a type name and a schema version. That meant two SDKs, two backup stories, and a Cosmos emulator nobody liked running on a laptop.

Step 1: SQL Server to Postgres

The relational half went first, and it is the boring half, which is a compliment. We switched EF Core to the Npgsql provider, loaded the data with pgloader, rewrote three stored procedures as LINQ and ported about twenty admin SQL reports. After a cutover in July, Postgres was the only relational database.

That left Cosmos DB as the last Azure dependency, and an odd one: we now had a perfectly good database that already understands JSON.

Step 2: make Postgres look like a Cosmos container

I didn’t want to rewrite twenty repositories and move data at the same time. So the first version kept the Cosmos shape exactly: one table, the system fields as columns and the document as jsonb.

CREATE TABLE dbo.cosmos_items (
pk text NOT NULL, -- Cosmos partition key
id text NOT NULL,
dtyp text NOT NULL, -- our document type
dver int NOT NULL DEFAULT 0,
rev int NOT NULL DEFAULT 0,
etag text,
ts bigint, -- Cosmos _ts, unix seconds
doc jsonb NOT NULL,
PRIMARY KEY (pk, id)
);

A new repository base class had the same methods as the Cosmos one, written in plain SQL against this table. Module by module, repositories switched base class, and the rest of the code didn’t notice.

The data copy found the first real bug. Our loader parsed each Cosmos document with Newtonsoft’s JObject.Parse, which by default turns ISO date strings into local DateTime values. Every timestamp in the copy came out shifted by the server's offset, and by a different amount in summer. Parsing with DateParseHandling.None keeps the strings exactly as Cosmos stored them.

To be sure, we compared the live Cosmos-backed API with the Postgres-backed one, endpoint by endpoint. Twelve of thirteen endpoints returned byte-identical JSON. The thirteenth returned the same items in a different order, from a list that was never sorted in the first place.

Step 3: one table per document type

One big table was a good bridge and a poor home. Every query had to filter by type first, and one type’s growth affected everybody’s indexes. So the next migration split it into a table per document type, each with a companion history table:

dbo.doc_support_ticket          (pk, id, dver, rev, etag, ts, doc jsonb)  PK (pk, id)
dbo.doc_support_ticket_history (pk, doc_id, rev, ts, doc jsonb) PK (pk, doc_id, rev)

The script runs as one transaction. It stops on any document type missing from its mapping and on any row-count mismatch, and it has a dry-run mode that runs every check and rolls back. On success it renames the old table instead of dropping it, so any code still pointing at it fails loudly rather than writing into a table nobody reads.

Step 4: let EF Core read the documents

Hand-written SQL repositories worked, but every filter was a string, and nothing checked them until runtime. EF Core 10 changes that. It can map a complex type to a JSON column, so the document becomes a typed property of the row and LINQ can reach into it.

Each row is a small generic entity: the system columns, plus the document.

public class DocEntity<TDoc> where TDoc : class, IDocument
{
public string Pk { get; set; } = "";
public string Id { get; set; } = "";
public int? DocVersion { get; set; } = TDoc.DocVersion;
public int Revision { get; set; } // optimistic concurrency token
public string? Etag { get; set; }
public long? Ts { get; set; } // unix seconds of the last write
public TDoc Doc { get; set; } = null!;
}

One extension method maps that onto a doc_ table. The interesting line is the last one: the document is a complex property stored as JSON in the doc column.

builder.ToTable(table, schema);
builder.HasKey(e => new { e.Pk, e.Id });
builder.Property(e => e.Revision).HasColumnName("rev").IsConcurrencyToken();
// … pk, id, dver, etag, ts
builder.ComplexProperty(e => e.Doc, d => d.ToJson("doc"));

A module’s context then reads like any other EF model. Nested objects and lists inside the document are declared too:

modelBuilder.Entity<DocEntity<Ticket>>().ToDocTable("doc_support_ticket", doc =>
{
doc.ComplexCollection(t => t.CcRecipients);
doc.ComplexCollection(t => t.SideConversations, sc => sc.ComplexCollection(c => c.Recipients));
});

And this is the part that made the whole move worth it. An ordinary LINQ query over fields of the document:

var tickets = await db.Tickets.AsNoTracking()
.Where(e => e.Pk == pk
&& e.Doc.Status == "open"
&& e.Doc.CreatedAt >= from
&& e.Doc.Subject.ToLower().Contains("invoice"))
.OrderByDescending(e => e.Doc.UpdatedAt)
.Take(50)
.ToListAsync();

becomes this SQL, exactly as Npgsql prints it:

SELECT d.pk, d.id, d.dver, d.etag, d.rev, d.ts, d.doc
FROM dbo.doc_support_ticket AS d
WHERE d.pk = @pk
AND (d.doc ->> 'Status') = @status
AND (CAST(d.doc ->> 'CreatedAt' AS timestamp with time zone)) >= @p
AND lower(d.doc ->> 'Subject') LIKE '%invoice%'
ORDER BY CAST(d.doc ->> 'UpdatedAt' AS timestamp with time zone) DESC
LIMIT @p3

Even a condition on a list inside the document works. “Tickets where one of the CC recipients is this address” turns into a jsonb_to_recordset subquery:

db.Tickets.Where(e => e.Pk == pk && e.Doc.CcRecipients.Any(c => c.Email == email));
-- WHERE d.pk = @pk AND EXISTS (
-- SELECT 1
-- FROM ROWS FROM (jsonb_to_recordset(d.doc -> 'CcRecipients') AS ("Email" text)) WITH ORDINALITY AS c
-- WHERE c."Email" = @email)

This is what our list pages run on now. A support agent picks “Status: In progress” from a column header, the API maps it to e.Doc.Status == value, and Postgres does the rest. There is no query language to learn and no SDK-specific filter syntax, just LINQ.

Rebuilding what Cosmos gave us for free

Cosmos does a handful of things without being asked. Each one needed a replacement, and most turned out to be a few lines.

  • Partition key: pk column, first part of the primary key, so every per-tenant query uses the index
  • _etag and optimistic concurrency: rev column as an EF concurrency token
  • _ts and ttl: ts column, plus a background sweep that deletes expired rows
  • Our own history documents: A _history table with JSON diffs, written in the same transaction
  • A counter document for ticket numbers: INSERT … ON CONFLICT … RETURNING
  • Full-text, vector and hybrid search: tsvector plus pgvector, fused in one query
  • Transactions within one partition: Ordinary transactions, across any tables, including the relational ones

Optimistic concurrency

A base DbContext stamps every added or changed document on save: a new timestamp and etag, and on updates the next revision. Because rev is the concurrency token, EF writes UPDATE … WHERE pk = @pk AND id = @id AND rev = @loaded. If somebody else saved first, no row matches and EF throws DbUpdateConcurrencyException, the same contract as an etag mismatch in Cosmos.

One subtle bug here: if a save fails, the entity in memory already carries the bumped revision. Retrying the same stale object could then match a row that another writer has moved to exactly that revision, and overwrite their change. The context puts the revision, timestamp and etag back to their loaded values when a save throws.

TTL

Cosmos deletes expired documents in the background. We do the same with a hosted service and one statement per table, which also removes the expired documents’ history:

WITH expired AS (
DELETE FROM dbo.doc_voice_file
WHERE ts IS NOT NULL
AND COALESCE((doc->>'ttl')::bigint, -1) > 0
AND ts + (doc->>'ttl')::bigint < extract(epoch from now())::bigint
RETURNING pk, id
)
DELETE FROM dbo.doc_voice_file_history h
USING expired e
WHERE h.pk = e.pk AND h.doc_id = e.id;

Version history you can read back

For some document types (knowledge base articles, support team settings) every update writes a row to the history table: a JsonDiffPatch diff between the stored document before and after the change. It happens inside the same transaction as the update, so a save rejected by the revision check leaves no history behind.

Because the diffs chain from revision to revision, any earlier version can be rebuilt by taking the current document and un-patching the diffs backwards. We read that result through EF itself, so an old revision of an article comes back as a normal typed entity, and the UI can show “revision 3 of 7” and restore it.

Sequential numbers

Tickets are numbered TK-1001, TK-1002 and so on, per tenant. In Postgres an atomic counter is one statement, and concurrent callers never get the same number:

INSERT INTO dbo.doc_counter AS c (key, value) VALUES (@key, @first)
ON CONFLICT (key) DO UPDATE SET value = c.value + 1
RETURNING c.value;

Hybrid search

This is the feature I wrote about on Cosmos in January. In Postgres the text side is a tsvector column with websearch_to_tsquery, the vector side is pgvector with the <=> cosine-distance operator, and reciprocal rank fusion combines the two rankings in a single round trip:

WITH t AS (
SELECT doc_uid, ordinal,
row_number() OVER (ORDER BY ts_rank_cd(content_tsv, websearch_to_tsquery('simple', @q)) DESC) AS rnk
FROM dbo.cn_search_chunks
WHERE … AND content_tsv @@ websearch_to_tsquery('simple', @q)
LIMIT @k),
v AS (
SELECT doc_uid, ordinal,
row_number() OVER (ORDER BY embedding <=> @qvec::vector) AS rnk
FROM dbo.cn_search_chunks
WHERE … AND embedding IS NOT NULL
ORDER BY embedding <=> @qvec::vector
LIMIT @k)
SELECT c.doc_uid, c.content,
COALESCE(@tw / (60 + t.rnk), 0) + COALESCE(@vw / (60 + v.rnk), 0) AS score
FROM dbo.cn_search_chunks c
LEFT JOIN t ON t.doc_uid = c.doc_uid AND t.ordinal = c.ordinal
LEFT JOIN v ON v.doc_uid = c.doc_uid AND v.ordinal = c.ordinal
WHERE t.rnk IS NOT NULL OR v.rnk IS NOT NULL
ORDER BY score DESC;

When a field deserves its own column

Not everything should stay inside the JSON. Two patterns came up.

Foreign keys you join or filter on all the time. Ticket messages are always loaded by ticket. That id moved out of the document into a real ticket_id column with an index. In EF it is a subclass of the row type with one extra property, and a migration copied the value out of the existing documents.

Counters. Knowledge base articles count views and “was this helpful” votes. If those numbers live inside the document, an editor who saves an article they opened ten minutes ago writes back ten-minute-old counts. As separate columns, EF is told never to write them on update, and the counting endpoints increment them with a single atomic UPDATE … SET views = views + 1.

e.Property(a => a.Views).HasColumnName("views")
.Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

Things that bit us

  • Old documents with missing keys. Documents written years ago don’t have the lists added since. EF hands a missing JSON key to the property as null, so collection setters turn null into an empty list. EF also writes straight into backing fields by default, bypassing those setters, so the base context tells it to prefer properties.
  • Dictionaries. A Dictionary<,> can't be a complex type. We map those with a value converter that keeps them as nested JSON objects. They read and write fine, but you can't filter on them in LINQ.
  • Timestamp precision. Newtonsoft wrote dates with 100-nanosecond ticks, while EF writes microseconds. The first EF save of every old document showed every date as changed in the history diffs, until the diff compared both sides at microsecond precision.
  • Testing. EF’s in-memory provider can’t materialize JSON complex collections, so in-memory tests were out. Every module’s repository tests run against a real Postgres in Docker, with a test database per context that is recreated from the EF model on each run.
  • Raw SQL bypasses the bookkeeping. ExecuteUpdate and ExecuteDelete are fast but skip the revision bump and the history rows. Anything that should be versioned has to go through SaveChanges.

What we got

One database to run, back up and restore. One script clones last night’s production backup into a local Docker Postgres, so a developer debugs against real data shapes instead of an emulator. Reports, admin queries and support questions can join a document table to the users table in one SQL statement, which was impossible across Cosmos and SQL Server.

Moving away from a vendor-specific database usually means giving something up. Here we gained typed LINQ over document fields, which was more pleasant than the Cosmos SDK’s queries ever were for us.

When I would still choose Cosmos DB

If you need multi-region writes, automatic global distribution, or partitions that grow far past what one server holds, Cosmos DB is built for exactly that and Postgres is not. Eport is a single-region service whose documents number in the hundreds per type, not billions. For a system like that, a document database inside the relational database is plenty, and you get a second database’s worth of operations back for free.

If you have moved off Cosmos DB, or decided not to, I’d like to hear what tipped it either way. Or if you would prefer to view more of the actual code, please feel free to ask.

Read, clap or comment on Medium →