Skip to content

perf(storage): batch entry writes when creating and refreshing feeds - #4609

Open
dave-atx wants to merge 3 commits into
miniflux:mainfrom
dave-atx:perf/create-feed-single-transaction
Open

dave-atx wants to merge 3 commits into
miniflux:mainfrom
dave-atx:perf/create-feed-single-transaction

Conversation

@dave-atx

@dave-atx dave-atx commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Creating or refreshing a feed runs several queries per entry. CreateFeed opens a transaction per entry and checks whether each entry exists (feed.go#L305-L333), RefreshFeedEntries does the same and then updates or inserts each entry and its enclosures one at a time (entry.go#L319-L365), and the processor calls IsNewEntry for every entry first (processor.go#L95). lib/pq spends two round trips on each parameterized query, so the time for a large feed grows with the database latency.

This PR has three commits:

  1. Create a feed and its entries in one transaction. entryExists was added in d610d09 to stop duplicate items within one feed document from violating entries_feed_id_hash_key. The RSS parser now disambiguates repeated GUIDs, but items with no GUID and the same link still share a hash, so duplicates are now skipped with an in-memory set, keeping the first one processed as before.
  2. Insert and update entries in batches. Entries and enclosures are written with unnest(), up to 500 entries and 64 MiB of text per statement, which keeps feeds with large contents well below Postgres's 1 GB message limit. An entry bigger than that gets a statement of its own.
    • RefreshFeedEntries runs in one transaction: one query for the IDs of the existing entries, a batched update, enclosure reconciliation for the existing entries, then a batched insert of the new ones.
    • The tombstone guard is kept. ON CONFLICT (feed_id, hash) DO NOTHING lets a concurrent refresh of the same feed skip an entry instead of failing.
    • The processor looks up stored and tombstoned hashes in one query instead of calling IsNewEntry per entry.
    • now() is the same for every statement in a transaction, so each created entry gets now() + (offset + position) * interval '1 microsecond' for created_at and changed_at. Entries are passed oldest first, so older entries still sort before newer ones.
    • Dates are sent in lib/pq's timestamp format (pq.FormatTimestamp), the same one it uses for time.Time parameters, so years ≤ 0 are still stored as BC dates. RFC 3339 has no BC notation, and Postgres rejects those years written that way.
  3. Skip updating entries that haven't changed. A refresh rewrote every existing entry even when nothing in it had changed, which writes a new row version and new full-text index entries each time. The batched UPDATE now only touches rows that differ. document_vectors is derived from title and content, so it isn't compared. Enclosures are still reconciled for every existing entry.

One behavior change: when a feed document lists the same item twice, refresh now keeps the first one processed (the last one in the document), as feed creation already did. Previously the other copy overwrote it.

Happy to split this into separate PRs if that's easier to review.

Motivation

Creating a podcast feed with 2,774 entries (https://feeds.megaphone.fm/GLT1412515089) took about 185 s on my instance, where Postgres is 2 - 10 ms away depending on the connection. That's longer than NetNewsWire's 120 s request timeout, so the client reported a failure while the server went on to create the feed.

Creating that feed through POST /v1/feeds, then force-refreshing it, against a local Postgres 17 with latency added by a TCP proxy:

Round trip Create: main Create: this PR Refresh: main Refresh: this PR
0.17 ms 11.9 s 1.3 s 15.3 s 1.4 s
1.5 ms 49.3 s 1.4 s 57.5 s 1.5 s
3.95 ms 117.7 s 1.5 s 139.6 s 1.6 s

These numbers predate the review fixes in commit 2, which don't add statements for this feed: the whole feed document is 5.5 MB, so the 64 MiB cap never splits a batch.

Postgres-side cost of a forced refresh of the same feed, measured with pg_stat_statements:

Refresh Entry UPDATE time Rows updated WAL
unchanged, before commit 3 455 ms 2,774 11 MB
unchanged, after 28 ms 0 9 kB
every title changed, before 426 ms 2,774 8 MB
every title changed, after 469 ms 2,774 11 MB

I've been running this on my instance (48 feeds, polling every 5 minutes). Over the first 23 minutes I measured after deploying it, Miniflux's statements went from about 9,800 calls and 10.5 s of database time per hour to about 1,200 calls and 1.4 s, and WAL from 32 MB to 0.6 MB per hour. The "before" numbers are a 3-week average that includes my own reading, so take the ratio as rough.

There are two side benefits:

  • The feed is no longer visible to the scheduler while it's being filled in. A newly created feed is immediately due for a refresh (next_check_at defaults to now()), and I saw the scheduler refresh a feed that was still being created.
  • A failed insert no longer leaves a partially imported feed or refresh behind. The flip side is that one failing entry fails the whole create or refresh, where main keeps the entries it committed before the failing one. The two causes raised in review (dates in year 0 or earlier, and very large batches) are handled above.

Testing

  • Added TestCreateFeedWithDuplicateEntries, which creates a feed from a local httptest server with two entries that share a hash. It passes on main and with this change, and fails with the unique-constraint error if the duplicate check is removed.
  • Added TestRefreshFeedUpdatesEntriesAndEnclosures, which refreshes a feed whose entries changed: an updated title and tags, an enclosure kept (same ID), added and removed, an unchanged entry that lost its enclosure, a new entry, and a new entry listed twice.
  • Added TestCreateAndRefreshFeedWithAncientDatesKeepsEntryOrder, which creates and then refreshes an Atom feed with entries dated 0000-12-31T00:00:00Z and 0001-01-01T00:00:00+05:00, and checks that created_at and changed_at increase from the bottom of the document up. Without the date fix it fails with pq: date/time field value out of range: "0000-12-31T00:00:00Z".
  • These tests skip unless the Miniflux server is on localhost, because the feed is served by the test process.
  • Added unit tests for splitting entries into batches by count and by size.
  • go test -race ./... and make integration-test pass.

Breaking changes

None.

Related issues

#4347 tried a similar single-transaction approach. The concerns raised there (identical created_at values within a batch) are handled in commit 2.

@dave-atx dave-atx changed the title perf(storage): create a feed and its entries in one transaction perf(storage): batch entry writes when creating and refreshing feeds Nov 1, 2026

@fguillot fguillot left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that PR #4347 tried a similar single-transaction approach, and the concerns I raised there apply here too: #4347 (comment)

Another behavioral change is that entry creation date becomes identical across the whole batch. In PostgreSQL, now() is evaluated once per transaction, so all entries inserted in the same batch will receive the same timestamp. The current processor assumes that older entries are inserted first and therefore have lower created_at values. This assumption no longer holds and may affect ordering/pagination behavior.

Main issues:

  1. One bad entry fails the whole batch. Dates are now sent as RFC3339Nano strings cast to timestamptz[]. Postgres rejects years ≤ 0 in that format (e.g. '0000-12-31T00:00:00Z'::timestamptz), where time.Time parameters were previously stored as BC dates. With one transaction, a single bad pubDate makes the feed impossible to create or refresh. The same applies if a 500-entry batch of large contents exceeds Postgres's 1 GB parameter limit.
  2. Identical created_at. now() is evaluated once per transaction, so every entry in the batch gets the same timestamp. The processor relies on older entries having lower created_at values, which affects ordering and pagination. Something like now() + (offset + e.position) * interval '1 microsecond' would keep them strictly increasing across chunks (same for changed_at).

@dave-atx
dave-atx force-pushed the perf/create-feed-single-transaction branch from 3af67a2 to d7b9cb1 Compare November 4, 2026 04:25
@dave-atx

dave-atx commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, and for the pointer to #4347. Both are fixed in the "insert and update feed entries in batches" commit:

  • Dates now go through pq.FormatTimestamp, the same encoding lib/pq uses for time.Time parameters, so years ≤ 0 are stored as BC dates again. Batches are also capped at 64 MiB of text on top of 500 entries; a single entry over that gets a batch of its own, which is no worse than today.
  • created_at and changed_at use now() + (offset + position) * interval '1 microsecond' as you suggested, with the offset carried across chunks.

I added an integration test that creates and then refreshes an Atom feed with entries dated 0000-12-31T00:00:00Z and 0001-01-01T00:00:00+05:00, and checks that both timestamps increase from the bottom of the document up. Before the fix it failed with pq: date/time field value out of range: "0000-12-31T00:00:00Z".

Any other error on a single entry still fails the whole transaction. Upstream also stops at the first failing entry, but keeps what it committed before that. If you'd rather keep that behavior, I can wrap each chunk in a savepoint and fall back to row-by-row inserts when a chunk fails.

Also, the first commit on its own still gives every entry the same now() during feed creation, since the second commit replaces that code. Happy to squash them if that's easier to review.

@dave-atx
dave-atx requested a review from fguillot November 11, 2026 07:14
Creating a feed opened a transaction per entry and ran two lookups that
can't find anything for a feed that doesn't exist yet: IsNewEntry in the
processor and entryExists in CreateFeed. With lib/pq each parameterized
query costs two round trips, so that's about 13 round trips per entry.
A podcast feed with 2,774 entries (feeds.megaphone.fm/GLT1412515089) took
about 185 s to create against a hosted Postgres, past the 120 s request
timeout of clients such as NetNewsWire.

The feed row and all entries are now inserted in a single transaction,
and the processor skips IsNewEntry when the feed has no ID yet.
entryExists was added in d610d09 to skip duplicate entries within one
feed document; that's now done with an in-memory set of hashes, keeping
the first occurrence as before. A side benefit is that the feed is no
longer visible to the scheduler while it's being filled in, and a failed
insert no longer leaves a partially imported feed behind.

Creating the feed above against a local Postgres with injected latency:

  round trip   before    after
  0.17 ms      13.5 s     5.9 s
  1.5 ms       51.0 s    21.0 s
  3.95 ms     119.8 s    48.6 s

Adds an integration test for duplicate entries during feed creation. It
passes on main and fails if the duplicate check is removed.
Creating or refreshing a feed ran several queries per entry, and with
lib/pq each parameterized query costs two round trips. A podcast feed
with 2,774 entries (feeds.megaphone.fm/GLT1412515089) needed tens of
thousands of round trips, so the time grew with the database latency.

Entries and enclosures are now written with unnest() in batches of up to
500 entries and 64 MiB of text, which keeps feeds with large contents
well below PostgreSQL's 1 GB message limit:

- CreateFeed inserts all entries and their enclosures in a few
  statements.
- RefreshFeedEntries runs in one transaction: it fetches the IDs of the
  existing entries in one query, updates them in a batch and reconciles
  their enclosures, then inserts the new entries. The tombstone guard is
  kept, and ON CONFLICT (feed_id, hash) DO NOTHING lets a concurrent
  refresh of the same feed skip an entry instead of failing.
- The processor looks up stored and tombstoned hashes in one query
  instead of calling IsNewEntry for each entry.

Since now() is the same for every statement of a transaction, each
created entry gets one more microsecond for created_at and changed_at
than the previous one, so older entries still sort before newer ones.

Dates are sent in lib/pq's timestamp format rather than RFC 3339, so
years before 1 AD are still stored as BC dates instead of failing the
whole batch.

When a feed document lists the same item twice, refresh now keeps the
first one processed, as feed creation already did; previously the second
copy overwrote the first.

Creating the feed above, then force-refreshing it, against a local
Postgres with injected latency:

  round trip   create before   after   refresh before   after
  0.17 ms           11.9 s     1.3 s          15.3 s    1.4 s
  1.5 ms            49.3 s     1.4 s          57.5 s    1.5 s
  3.95 ms          117.7 s     1.5 s         139.6 s    1.6 s

Adds integration tests for refreshing a feed whose entries and
enclosures changed, and for entries dated in year 0 keeping their
creation order across feed creation and refresh.
A refresh rewrote every existing entry in the feed even when nothing in
it had changed. Each of those updates writes a new row version and new
full-text index entries, which made the entry UPDATE the largest source
of database time on my instance.

The batched UPDATE now only touches entries whose stored fields differ
from the feed. document_vectors is derived from title and content, so it
isn't compared. Enclosures are still reconciled for every existing entry.

Force-refreshing a podcast feed with 2,774 entries against a local
Postgres:

  refresh           UPDATE time   rows updated   WAL     wall time
  unchanged before       455 ms           2774   11 MB      1.44 s
  unchanged after         28 ms              0    9 kB      0.98 s
  all changed before     426 ms           2774    8 MB      1.38 s
  all changed after      469 ms           2774   11 MB      1.44 s
@dave-atx
dave-atx force-pushed the perf/create-feed-single-transaction branch from d7b9cb1 to a7fe92e Compare December 1, 2026 19:19

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants