Repository navigation
Conversation
fguillot
left a comment
There was a problem hiding this comment.
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:
- One bad entry fails the whole batch. Dates are now sent as
RFC3339Nanostrings cast totimestamptz[]. Postgres rejects years ≤ 0 in that format (e.g.'0000-12-31T00:00:00Z'::timestamptz), wheretime.Timeparameters were previously stored as BC dates. With one transaction, a single badpubDatemakes 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. - 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 lowercreated_atvalues, which affects ordering and pagination. Something likenow() + (offset + e.position) * interval '1 microsecond'would keep them strictly increasing across chunks (same forchanged_at).
3af67a2 to
d7b9cb1
Compare
|
Thanks for the review, and for the pointer to #4347. Both are fixed in the "insert and update feed entries in batches" commit:
I added an integration test that creates and then refreshes an Atom feed with entries dated 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 |
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
d7b9cb1 to
a7fe92e
Compare
Description
Creating or refreshing a feed runs several queries per entry.
CreateFeedopens a transaction per entry and checks whether each entry exists (feed.go#L305-L333),RefreshFeedEntriesdoes the same and then updates or inserts each entry and its enclosures one at a time (entry.go#L319-L365), and the processor callsIsNewEntryfor 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:
entryExistswas added in d610d09 to stop duplicate items within one feed document from violatingentries_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.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.RefreshFeedEntriesruns 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.ON CONFLICT (feed_id, hash) DO NOTHINGlets a concurrent refresh of the same feed skip an entry instead of failing.IsNewEntryper entry.now()is the same for every statement in a transaction, so each created entry getsnow() + (offset + position) * interval '1 microsecond'forcreated_atandchanged_at. Entries are passed oldest first, so older entries still sort before newer ones.pq.FormatTimestamp), the same one it uses fortime.Timeparameters, so years ≤ 0 are still stored as BC dates. RFC 3339 has no BC notation, and Postgres rejects those years written that way.UPDATEnow only touches rows that differ.document_vectorsis 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:mainmainThese 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:UPDATEtimeI'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:
next_check_atdefaults tonow()), and I saw the scheduler refresh a feed that was still being created.mainkeeps 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
TestCreateFeedWithDuplicateEntries, which creates a feed from a localhttptestserver with two entries that share a hash. It passes onmainand with this change, and fails with the unique-constraint error if the duplicate check is removed.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.TestCreateAndRefreshFeedWithAncientDatesKeepsEntryOrder, which creates and then refreshes an Atom feed with entries dated0000-12-31T00:00:00Zand0001-01-01T00:00:00+05:00, and checks thatcreated_atandchanged_atincrease from the bottom of the document up. Without the date fix it fails withpq: date/time field value out of range: "0000-12-31T00:00:00Z".go test -race ./...andmake integration-testpass.Breaking changes
None.
Related issues
#4347 tried a similar single-transaction approach. The concerns raised there (identical
created_atvalues within a batch) are handled in commit 2.