How Sibling Topics Share Search Results Without Receiving the Same Document
Three topics generated from one keyword kept receiving the same source document. I fixed it with a PostgreSQL lease, a re-check at commit time, and a UNIQUE constraint, and compared that design with FOR UPDATE and advisory locks.
On this page
- Introduction
- 1 Siblings receiving the same document was intentional at first
- 2 I kept the search and changed the allocation
- 3 Three workers reading the pool at once pick the same document
- 4 I combined a lease, a commit-time re-check, and a UNIQUE constraint
- 5 What I learned by comparing other locking approaches
- 6 Assignments stay stable through failures and retries
- 7 Results from production data, and limits
- Conclusion
Introduction
Wiblog is a blogging SaaS for business owners. A business registers keywords for its field, and AI writes posts in that field every day and publishes them to the blog. I built the pipeline that creates topic candidates and collects the sources each post is based on.
Before a post is written, the pipeline goes through these steps.
- It creates three topic candidates from one keyword. I call that keyword the seed, and candidates from the same seed sibling topics.
- A separate worker runs for each topic and finds its sources. Each topic receives up to three general documents, plus at most one each from Naver Blog, YouTube, and Namuwiki. I call those last three places platform slots.
- It builds an outline from the collected sources and generates the post.
The problem appeared in step 2. Three sibling topics were receiving the same Naver Blog post and the same YouTube video as sources. The three posts had different titles but cited the same material.
This post answers one question.
How can several topics share search results and still never receive the same document when they are processed at the same time?
The short answer is “I used a lease and a UNIQUE constraint.” This post also explains why a simpler lock was not enough and which new problem a lease introduces. The comparison of locking approaches in section 5 is not a record of what I evaluated at the time. I wrote it after the implementation, while studying the underlying principles again.
1. Siblings receiving the same document was intentional at first
Platform searches shared their results between siblings
When the general search returns no document for a platform, the pipeline fills that slot with a site: search. This supplementary search uses only the seed, not the topic title. The scope is already narrowed to one site, so adding more words leaves too few results.
As a result, three sibling topics sent exactly the same query three times. The supplementary search cost five times as much as a general search and accounted for KRW 14 of the KRW 19.6 search cost per topic. In August I cached the result per seed so that siblings paid for it only once.
The premise at the time was this. A platform slot holds “the representative document for the subject,” so siblings receiving the same document was the intended design, not a problem. The cache did not change that result. It only removed the duplicate payment. It stored one best document per platform.
When the premise changed, the same structure became the problem
In October I reviewed topic quality again and changed that premise. Sibling topics start from the same seed, but they have to answer different questions such as price, reviews, or cancellation rules. If three posts cite the same blog post, their evidence overlaps and they read as similar posts.
I aggregated the sources of completed outlines from the production database for the two weeks before the change (2026-09-18 to 10-02). The table compares platform source URLs within groups that had two or more siblings.
| Item | Value |
|---|---|
| Sibling groups | 180 |
| Groups with at least one platform source | 139 |
| Groups where two or more siblings received the same document | 113 (81.3%) |
| Platform source assignments | 568 |
| Assignments of a document shared with a sibling | 394 (69.4%) |
These numbers count only exact URL matches. Different URL forms of the same video were not detected, so the real overlap may have been higher.
2. I kept the search and changed the allocation
There were several ways to remove the overlap. I decided not to do three of them.
- Do not search separately for each sibling. That would bring back the search cost I had cut in August.
- Do not narrow the supplementary query per topic. Adding words to a
site:search leaves too few results. - Do not relax the filters when documents run short. Only documents that pass the commercial and relevance filters are used.
Instead, I changed how many results are kept and how they are handed out.
- For each platform, the pool keeps up to three documents that passed the filters.
- Siblings from the same site, the same generation batch, and the same seed each take one document that no one else has received yet.
- If no document is left, the slot stays empty. The same document is never used to fill the count.
The following sections use one example. One seed produced topics A, B, and C, and the Naver Blog pool holds documents 1, 2, and 3. A should receive document 1, B document 2, and C document 3.
I also defined what counts as the same document. A URL can differ while pointing to the same document, so the document key is built from the canonical post identifier for Naver, the video ID for YouTube, and the article path for Namuwiki.
3. Three workers reading the pool at once pick the same document
The allocation rule is simple: “take the first document in the pool that has not been assigned.” If workers ran one at a time, this would be enough.
However, the workers for sibling topics start almost simultaneously. The diagram below shows what happens when workers A and B read the same pool without a lock.
Both workers read the same state, “document 1 is not assigned yet,” so they reach the same conclusion. This is a typical race condition that occurs when another worker can slip in between a read and a write.
So everything from reading the pool to recording the assignment must be executed by one worker at a time. Up to this point, a single lock looks sufficient.
The section to lock contains an external call that takes minutes
The difficulty lies in what happens inside that section. A worker runs in this order.
- It reads the pool and the siblings’ assignments.
- If no document is left and the supplementary search has not run yet, it calls the external search API.
- It picks a document and records the assignment.
The search in step 2 waits up to 120 seconds per attempt and retries once. In the worst case it takes several minutes. Only one sibling should run this search, too. If three workers decide at the same time that the pool is empty, the same search is paid for three times.
In short, the lock has to be held across work that can take minutes outside the database. This condition determined which locking approach I chose.
4. I combined a lease, a commit-time re-check, and a UNIQUE constraint
The approach I chose expresses the lock not through a database locking feature but as data written in a row. The pool row records who is using it and until when. This is called a lease. Here is the whole flow first.
A database transaction is open only briefly, in step 1 and in steps 4 and 5. During the search in step 3, the worker holds no database connection. The sections below explain what each mechanism prevents.
The lease: acquired in one statement, and the connection is returned at once
INSERT INTO research_platform_pool (cache_key, lease_owner, lease_until)VALUES ($key, $owner, clock_timestamp() + interval '5 minutes')ON CONFLICT (cache_key) DO UPDATE SET lease_owner = EXCLUDED.lease_owner, lease_until = EXCLUDED.lease_until WHERE research_platform_pool.lease_until IS NULL OR research_platform_pool.lease_until < clock_timestamp()RETURNING cache_key;This statement handles “if the row does not exist, or the lease is empty, or it has expired, I take it” in one step. If a row is returned, the acquisition succeeded. If not, another worker holds the lease. The check and the change happen inside one statement, so when two workers run it at the same time only one succeeds.
A worker that fails to acquire the lease retries after 250 ms and gives up after 310 seconds. $owner is a UUID generated on every run.
The lease lasts five minutes because it has to be longer than the worst-case duration of the work. I set it longer than two 120-second search attempts plus the retry delay.
A lease alone is not enough: the worker that wakes up after expiry
A lease must have an expiry. If a worker dies while holding it, nobody else releases it. But the expiry creates a new problem.
- Worker A acquires the lease and starts searching.
- A stalls for more than five minutes. The cause could be network delay or a paused process.
- The lease expires, worker B takes it, and B is assigned document 1.
- A wakes up. A still believes it owns the lease, so it tries to record document 1 based on the state it read earlier.
From A’s point of view, there is no way to know it was stalled. So the database has to check again at the moment of the write.
The commit-time re-check: asking again right before writing
The transaction that saves the assignment begins with this statement.
UPDATE research_platform_pool SET state = $stateWHERE cache_key = $key AND lease_owner = $owner AND lease_until > clock_timestamp();-- If the number of updated rows is not 1, throw and roll back the whole transactionIn the scenario above, lease_owner already holds B’s value, so A updates no rows. The code treats this as a platform_pool_lease_lost error and rolls back everything, including the assignment record. Blocking a late write in this way is called fencing.
The important point is that this check and the assignment record are in the same transaction. The UPDATE locks the pool row, so no other worker can take the lease between the check and the write. This transaction opens only after the search has finished, so it is short.
There is also a reason for using clock_timestamp() instead of now(). now() returns the time the transaction started, while clock_timestamp() returns the actual time the statement runs. And because every comparison uses the single clock of the database server, clock drift between worker machines does not change the decision.
The UNIQUE constraint: the last line of defense if the logic above is wrong
CREATE TABLE research_platform_assignments ( scope_key text NOT NULL, -- site + generation batch + seed topic_id bigint NOT NULL, slot text NOT NULL, -- youtube | namu | naver_blog document_key text, -- NULL for an empty slot -- ... PRIMARY KEY (scope_key, topic_id, slot), UNIQUE (scope_key, slot, document_key));The lease and the re-check are application logic. A bug in the code, or a later write path that bypasses this route, could break them. UNIQUE (scope_key, slot, document_key) makes the database reject a second assignment of the same document in the same scope, no matter which path it comes from.
An empty slot has a NULL document_key. PostgreSQL treats NULL values as distinct in a UNIQUE constraint, so several siblings can hold empty slots without violating it.
The table summarizes what each of the three mechanisms prevents.
| Mechanism | Failure it prevents | What happens without it |
|---|---|---|
| Lease | Two workers reading the same state and picking the same document | Duplicate assignment and duplicate payment for a search |
| Commit-time re-check | A worker with an expired lease writing late | A record that conflicts with the new owner’s assignment |
| UNIQUE constraint | Any duplicate, including ones caused by code mistakes | Duplicates remain silently when the two above are wrong |
5. What I learned by comparing other locking approaches
After the implementation, I went back to the question “PostgreSQL already has locking features, so why did I have to build one?” This section is what I studied while answering it.
SELECT … FOR UPDATE: the transaction must stay open during the search
The simplest approach is to open a transaction, lock the pool row with FOR UPDATE, search, record, and commit. If the worker dies, the connection drops and the lock is released automatically, so there is no expiry to manage.
But this approach keeps a transaction open for the minutes the search takes.
- It holds a connection. A transaction is bound to one connection. The searching worker and the sibling workers waiting behind it each hold one.
- A long-running transaction affects other tables. PostgreSQL cannot clean up row versions that the oldest open transaction might still see. If multi-minute transactions keep appearing, cleanup of dead rows (vacuum) is delayed even on unrelated tables.
- It does not fit the defaults of the tool I used. Prisma’s interactive transactions time out after five seconds by default. The limit can be raised to minutes, but the default also tells you that transactions are not usually used that way.
Advisory locks: a poor fit for a connection pool
An advisory lock is a lock on an arbitrary key, unrelated to any row. There are two kinds.
- Transaction-level (
pg_advisory_xact_lock) is released when the transaction ends. LikeFOR UPDATE, it needs a long transaction. - Session-level (
pg_advisory_lock) is bound to the connection (session), independent of transactions. It needs no long transaction, but the lock must be released on the same connection that acquired it.
The worker sends queries through a connection pool, so there is no guarantee that the locking query and the unlocking query use the same connection. If the release is sent on a different connection, the lock is not released, and it stays while the original connection returns to the pool and is reused. Avoiding this requires the worker to hold a dedicated connection for the whole search, which brings back the problem of holding a connection.
The three approaches side by side
| Approach | Holds a connection during search | Long transaction | When the worker dies | What you implement yourself |
|---|---|---|---|---|
FOR UPDATE | Yes | Yes | Released immediately | Nothing |
| Advisory lock (session) | Yes (dedicated connection) | No | Released immediately | Connection pinning |
| Lease | No | No | Waits until expiry (5 minutes) | Expiry, re-check, wait and retry |
A lease holds no database resource during the search, but you have to implement what the database used to do for you. If the locked section is short, FOR UPDATE is the simpler and safer choice. In this case the section contained an external call that takes minutes, so a lease was the right fit.
What was possible because the lease and the data live in the same database
I learned one more thing while studying. A commonly cited weakness of distributed locks is that the lock lives in one store and the data in another, so the lock cannot be re-checked at the moment of the write. A client that acquires a lock, stalls, and wakes up will write data while trusting an expired lock.
In this implementation, the lease and the assignment data are in the same PostgreSQL database. That is why the re-check from section 4 could go into the same transaction as the assignment record. With a lock in an external store, I would have needed a separate mechanism that issues an increasing token and has the data side verify it.
6. Assignments stay stable through failures and retries
Concurrency is not the only thing that can disturb assignments. Workers retry after failures, and topics are sometimes deleted.
A successful assignment is kept
If topic A receives document 1 and then fails at a later stage and retries, A receives document 1 again. If each retry took a different document, fewer documents would be left for the siblings.
Document 1 is not released even when topic A is deleted. For this reason the assignment table has no foreign key to the topic. With a foreign key and cascading delete, the assignment would disappear with the topic and the document could be assigned to a sibling. The document may already have been used in A’s outline, so within the scope it stays A’s until the end.
Empty slots are handled differently depending on the reason
A slot can be empty for more than one reason. Without separating the reasons, “there was no document” and “the search failed” end up as the same result.
| Reason | Meaning | On retry |
|---|---|---|
no_results | The search ran but found no document on that platform | Left as is |
filtered_out | Documents existed but none passed the filters | Left as is |
already_assigned | Siblings took every document that passed | Left as is |
search_failed | The search request failed | Allocation is tried again |
partial_response | Only part of the search response came back | Allocation is tried again |
An empty slot after a search that completed normally is treated as a final result and is not searched again. Only empty slots caused by a failure or a partial response are recovered on retry. This keeps a temporary outage from being fixed in place as “no document.”
Two defects found in review
A separate code review after the implementation found two defects. Neither showed up on the normal path.
- Empty slots becoming permanent on retry: The first implementation always kept an assignment once it was recorded. So a slot left empty by a search failure was never filled on retry. I changed it so that only empty slots whose reason is
search_failedorpartial_responsecan be overwritten, as in the table above. - The pool’s lifetime being extended at the expiry boundary: The pool is discarded after seven days. But if the seven-day boundary passed during a search, a pool that should have expired was committed and gained another seven days. I moved the expiry decision from commit time to the moment the pool is read under the lease.
I fixed both defects and added regression tests to confirm the fixes.
7. Results from production data, and limits
Concurrency was tested with real SQL
The behavior of the lease and the constraint cannot be verified with fake objects that imitate queries. I ran real SQL on PGlite, which runs PostgreSQL in-process, and tested these cases.
- Three siblings requesting allocation at the same time receive different documents
- The supplementary search runs only once among siblings
- The reason is recorded correctly for document shortage, partial response, search failure, and retry
- The same seed in a different site or batch is not mixed in
- The owner of an expired lease fails to commit, and the UNIQUE constraint rejects duplicates
Overlap between siblings dropped to zero
After deploying on 2026-10-02, I aggregated two weeks of outlines with the same method as in section 1.
| Item | Before (2 weeks from 09-18) | After (2 weeks from 10-02) |
|---|---|---|
| Sibling groups with a platform source | 139 | 1,727 |
| Groups where two or more siblings received the same document | 113 (81.3%) | 0 |
| Platform source assignments | 568 | 6,465 |
| Assignments of a document shared with a sibling | 394 (69.4%) | 0 |
The two periods have different sample sizes because topic generation grew considerably after the deploy. Across the whole assignment table, 46,561 topics had gone through this path by 2026-11-30, and no document was held by two siblings.
The cost of avoiding overlap: 9.4% empty slots
Removing duplicates meant some slots ended up empty. I aggregated how the 2,889 slots of 963 topics ended during the first 48 hours after the deploy, by reason.
| Reason | Slots | Share |
|---|---|---|
| Assigned | 1,576 | 54.6% |
No search results (no_results) | 810 | 28.0% |
Already taken by a sibling (already_assigned) | 271 | 9.4% |
Dropped by filters (filtered_out) | 193 | 6.7% |
Search failed (search_failed) | 39 | 1.3% |
Of the 810 no_results slots, 696 are Namuwiki. Many subjects simply had no Namuwiki article.
The 271 already_assigned slots (9.4%) are the direct cost of this change. Under the old approach they would have been filled with the same document a sibling had. I judged that leaving them empty is better than citing the same document repeatedly, but it is also true that some topics now have fewer sources.
What I did not verify
- I did not verify source quality. These results show only that documents no longer overlap. Allocation follows processing order and does not compare the topic’s question with the document’s content. There is no guarantee that a topic asking about price receives a document about price.
- The waiting scheme is simple. A worker waiting for the lease retries every 250 ms. There is no guarantee that the worker that waited first gets it first, and if the lease holder dies, siblings wait up to five minutes.
- The lease duration is tied to the search timeout. If the search timeout is raised, the lease duration has to be raised with it. For now this relationship exists only as a code comment.
Conclusion
Siblings receiving the same document was intended behavior at first. When I changed the premise for a platform slot from “the representative document for the subject” to “different evidence for each sibling,” I kept the structure that shares search results and changed only how they are handed out.
The hard part of the implementation was not the allocation rule but the lock. The section to lock contained an external search that takes minutes, so it could not be wrapped in a transaction, and using a lease brought the problem of an expired worker writing late. I blocked that with a commit-time re-check and added a UNIQUE constraint in case that logic was wrong.
I learned two things from this work. First, when choosing a locking approach, look first at how long the lock is held and what happens during that time. Second, a lock with an expiry has to be paired with a re-check at the moment of the write.
After the change, overlap between siblings dropped to zero, and in exchange 9.4% of slots were left empty. The next thing to verify is whether the assigned documents actually answer each topic’s question.
Comments