Brigoš did not have a traffic problem. It had a data-access problem.

Brigoš is a marketplace for short-term jobs, built with Next.js and Firebase/Firestore. In production, it eventually hit RESOURCE_EXHAUSTED: the 50,000 daily Firestore read quota had been consumed. The marketplace was still relatively small. I needed to understand how ordinary page requests could spend that many reads.

The answer was read amplification. A page displaying a handful of jobs could load a large dataset, discard most of it, then repeat some of those reads in the browser. Search traffic and sitemap requests multiplied that cost. I first bounded the existing queries, then introduced PostgreSQL as a public search projection while keeping Firestore authoritative.

The rollout exposed a synchronization issue after writes resumed. I used the legacy read mode temporarily, fixed the issue and reconciled the projection again before completing the rollout. PostgreSQL now serves public search in production; Firestore remains the source of truth.

Finding the actual bottleneck

I traced the reads behind the rendered pages rather than counting the items visible on screen. Marketplace routes loaded large, global datasets before filtering and sorting in application code. City pages reused the same inventory loaders and narrowed the results afterward. The homepage fetched more data than it displayed. Browser initialization duplicated some work already done on the server.

Filters often operated over inventory that had already been loaded. Server-side execution did not make that work free: Firebase Admin SDK queries still consume Firestore reads. Moving a global query out of the browser changed where it ran, not how many documents it read.

Pagination in the interface hid the problem. Rendering one page of results did not mean fetching one page of records: the application had already read the larger collection before slicing it. Moving between pages could look efficient while the expensive work remained upstream.

Sitemap generation was another multiplier. It repeatedly scanned listings and profiles, outside the user-facing search flow. With representative collection sizes, just 24 sitemap requests per day could account for roughly 50,400 Firestore reads. That calculation was not a production traffic measurement; it showed how little crawler activity was needed to exhaust the quota under that access pattern.

This changed what I considered production traffic. SEO infrastructure needed a read budget too. A fast page could still sit behind an expensive sitemap generator or a browser bootstrap that quietly repeated its queries.

Bounded queries first

The first phase removed unnecessary global browser Firestore initialization, bounded server queries and introduced cursor pagination. I restructured public loaders and reduced duplicate hydration. Instead of loading everything and filtering later, loaders fetched limited results.

I also fixed sitemap generation so it no longer repeated the same inventory scans unnecessarily, and used ISR and caching so warm requests could reuse generated output. The goal was predictable database cost per request as well as fewer reads.

Why query optimization wasn’t enough

The marketplace needed text search, categories, city and location filters, radius queries, sorting and TOP listing ordering. It also needed owner queries, counts and facets. Firestore could support parts of this, but combining those requirements in public loaders was becoming difficult to maintain and inefficient.

I separated public discovery from authoritative storage. A dedicated query layer could identify a small result set before Firestore hydration began, rather than forcing increasingly complex search logic into global inventory reads.

Firestore remains the source of truth

I deliberately kept the business database in Firestore. It still owns listings, profiles, reviews, user and account state, and authoritative mutations. PostgreSQL did not replace it or become a second owner of business data.

PostgreSQL held a derived, disposable public search projection. If it drifted or needed rebuilding, I could reconstruct it from Firestore. Losing confidence in the projection would not require restoring business data. That separation also made it possible to ship the new read path behind a mode switch.

A PostgreSQL search projection

The new flow starts with PostgreSQL. Its public search index handles text search, category and city/location predicates, geographic and radius queries, ordering, pagination, counts and facets. It returns matching IDs; Firestore hydrates only the actual records needed for the page.

Old read path

  1. Firestore
  2. Read large collection
  3. Filter / sort in application
  4. Render small page

New read path

  1. PostgreSQL
  2. Search / filter / sort → IDs
  3. Firestore
  4. Hydrate selected records
The query layer selects candidates; Firestore supplies the authoritative records for the page.

This bounded Firestore work by the selected records rather than the size of the searchable collection. It also kept the responsibilities explicit: PostgreSQL answered public discovery queries, and Firestore supplied business data. The projection could become temporarily stale, so its synchronization and operational controls mattered as much as the SQL queries.

Keeping two databases consistent

A second datastore raises a concrete consistency problem: Firestore may accept a mutation while PostgreSQL is temporarily unavailable. I avoided naive dual writes that would make both systems responsible for the same authoritative change.

Each write creates a durable projection journal entry and an integer revision alongside the business mutation in a Firestore transaction. The journal records work that still needs to reach PostgreSQL. A PostgreSQL failure does not invalidate a successful Firestore mutation; the projection can catch up later.

  1. User mutation
  2. Firestore transaction
    Authoritative business data Projection journal / revision
  3. Projector
  4. PostgreSQL
Business data and durable projection work are recorded together. Projection application follows separately.

The projector applies revisions idempotently. Replaying the same work must be safe, and an older revision must not overwrite a newer one. Revision checks make the result independent of whether an event arrives late or a delivery is retried.

Deletes need the same protection. Removing the searchable record while forgetting its revision would allow an older update to recreate it. Retaining deletion revision information, a tombstone, prevents that resurrection. Absence alone is not enough to establish which event wins.

These mechanisms preserve Firestore’s authority; they do not make the two databases synchronously identical. I still needed reconciliation to detect differences, and a safe way to stop depending on the projection if synchronization failed.

A controlled production migration

The application supports two public query modes: legacy reads Firestore directly; projection uses PostgreSQL for public search and bounded Firestore hydration where required. I deployed the new architecture in legacy mode first, so introducing the code did not immediately change public reads.

I provisioned PostgreSQL and verified its schema, extensions, indexes and triggers. The application used a restricted runtime role with only the permissions it required, rather than migration or superuser privileges.

With writers paused, I ran a dry-run backfill, applied it and drained the projection journal. Full Firestore ↔ PostgreSQL reconciliation and a separate readiness gate came next. Only after both passed did I enable projection reads and run production smoke tests, then resume writes and monitor the live path.

  1. Deploy in legacy mode
  2. PostgreSQL provisioned
  3. Schema checks
  4. Pause writers
  5. Dry run
  6. Backfill
  7. Journal drain
  8. Reconcile
  9. Readiness
  10. Projection
  11. Smoke test
  12. Resume writes
  13. Monitor / verify
  14. Production complete
Reconciliation and readiness gated the read switch. Verification continued after writes resumed, including recovery from the synchronization issue described below.

Reconciliation processed all expected source records and confirmed that the projection was synchronized, with zero mismatches. Readiness verification also succeeded. Finishing a migration command was not the correctness check: reconciliation compared source and projection, and readiness was a separate gate before production reads moved.

Production logs showed SQL queries serving the homepage, marketplace and city search, with Firestore reduced mostly to bounded hydration reads. Those checks established that the backfilled projection and public query path worked. Resuming writes tested the ongoing synchronization path.

A rollout issue, then recovery

After writes were enabled, a production smoke test exposed a projection synchronization issue. I temporarily switched public reads back to legacy mode, preserving authoritative Firestore state and journal history. I did not delete journals, modify production business records or reset revisions to force agreement.

I fixed the underlying issue, synchronized the projection and reconciled it again. The rollout then completed successfully. The temporary fallback kept the failure bounded and recoverable while I repaired the derived system.

Results, with a defined scope

The representative fixtures and benchmarks showed substantial reductions in Firestore reads. These compare the original data-access paths with optimized paths; they are not universal production costs, a production billing comparison, or an isolated measure of PostgreSQL’s contribution.

8,659 → 456 Firestore reads in a representative crawler workload · ~94.73% reduction
Representative fixture / benchmark Firestore reads
WorkloadBeforeAfterReduction
Homepage · cold server12912~90.7%
Marketplace · cold server12044~63.3%
City page12034~71.7%
Empty city1203~97.5%
Small public profile1219~92.6%
Sitemap · cold840120—
Sitemap · warm after ISR regeneration8400—
Anonymous marketplace · combined30044~85.3%
Anonymous listing detail · combined1834~97.8%
Anonymous public profile · combined30113~95.7%

Combined anonymous measurements include server and browser reads. Cold-server measurements describe the server path. The warm sitemap result depends on reusing generated output after ISR regeneration; generating it again still has a cost.

The empty-city result was particularly useful: a query with no matches should not require reading the global marketplace. The crawler benchmark showed the aggregate effect of fixing access patterns across repeated requests, including work outside the visible interface.

The production architecture today

Brigoš now runs in projection query mode in production. PostgreSQL actively serves public search, filtering, sorting, geographical queries, pagination, counts and facets. The Next.js application uses bounded Firestore hydration where required.

Firestore remains authoritative for business records, mutations and source state. Durable journals and revisions connect it to the derived projection; reconciliation tooling, readiness checks and the legacy read mode remain available for verification and recovery. The final production rollout completed successfully.

What I learned

  • Rendering 20 records does not mean reading 20 records. Frontend pagination can hide an expensive backend; filtering and limits need to constrain the database work.
  • Data-access architecture matters more than micro-optimizations. The largest problem was the shape of the reads, not a slow function.
  • Crawlers and SEO infrastructure are production traffic too. Their repeated scans can dominate a read budget.
  • Secondary indexes and projections should be disposable, with an unambiguous authoritative source and a reconciliation path.
  • Performance engineering includes failure engineering. Observability, reconciliation and rollback made failures bounded, recoverable and reversible.

PostgreSQL solved the scaling problem. The journal, reconciliation tooling and rollback path made it possible to deploy the change safely.