We are going to design a search indexing pipeline that includes:
Deduplication: Remove duplicate documents before indexing.
Versioning: Track versions of documents so that updates and deletions are handled.
Reindex/Backfill: Ability to reindex the entire dataset or backfill new data.
Monitoring: Monitor the pipeline for health, performance, and data quality.
We assume a distributed system with scalability in mind.
Components:
Data Source: Could be a database, log stream, or any source of documents.
Ingestion Service: Pulls data from the source and sends to a message queue for processing.
Preprocessing Service (Deduplication and Versioning):
Deduplication: Identify and remove duplicates. We can use a hash of the document content (or a combination of fields) to detect duplicates.
Versioning: Assign a version to each document. When a document is updated, we increment the version. Deletions are handled by marking as deleted (tombstone) and not indexing the latest version if it's marked as deleted.
Indexing Service: Takes the preprocessed documents and indexes them in the search engine (e.g., Elasticsearch, OpenSearch).
Storage for Versioning and Deduplication State: We need to store the state (like the latest version of each document and the hash for deduplication) so that we can compare new data with existing. This could be a database (like PostgreSQL) or a key-value store (like Redis or Cassandra).
Reindex/Backfill Service: A service that can trigger a full reindex or a backfill for a specific time range or set of IDs. This might involve:
Reindex: Clear the index and then reindex everything from the source, possibly with a new mapping.
Backfill: Index data that was missed or needs to be reindexed for a specific period.
Monitoring:
Metrics: Track the number of documents processed, duplicates removed, indexing latency, errors, etc.
Alerts: Set up alerts for failures or performance degradation.
Dashboards: Visualize the metrics and health of the pipeline.
Steps in the pipeline:
Ingestion:
Pull data from the source in batches or stream.
Send each document (or batch) to a message queue (like Kafka) for preprocessing.
Preprocessing:
For each document:
a. Compute a hash (or use a natural key if available) to identify the document.
b. Check the storage for the latest version of this document (by key) and the hash of the last indexed version.
c. If the hash is the same, then it's a duplicate of the last indexed version -> skip.
d. If the hash is different, then it's an update or a new document.
e. If the document has a deletion marker (or is marked as deleted in the source) then we create a tombstone (version increment but mark as deleted).
f. Otherwise, we increment the version and update the storage with the new hash and version.
Send the document (with version and deletion marker if any) to the indexing queue.
Indexing:
Consume from the indexing queue and index the document in the search engine.
In the search engine, we might use the document key as the document ID so that updates overwrite and deletions set a flag or remove the document.
Reindex/Backfill:
We might have a separate service that can trigger a reindex by:
a. Clearing the index (or creating a new index and then switching alias).
b. Reading all documents from the source (maybe with a cursor or by time range) and sending them through the same preprocessing and indexing steps, but without checking for duplicates? Or with checking?
For reindex, we want to rebuild the entire index from scratch, so we should index every document we read, but we still want to version them correctly?
Actually, for a full reindex we might not need to worry about versioning because we are starting fresh. But if we are backfilling, we might be inserting into an existing index and then we need to consider versioning to avoid conflicts.
Alternatively, we can design the indexing to be idempotent and use the same versioning logic. So when reindexing, we treat each document as if it's the latest version from the source. But note: if we are reindexing the entire dataset, we are going to reset the versioning state?
Let's clarify:
For a full reindex:
- We want to throw away the old index and build a new one from the current state of the source.
- We also want to reset the versioning state? Not necessarily, because the versioning state is used to detect changes from the source. If we reindex from the source, we are essentially getting the latest version of every document. We can reset the versioning state to the versions we are about to index? Or we can keep the versioning state and then when new changes come, they will be compared with the reindexed state.
However, if we are backfilling (for example, we missed some documents for a time range), then we want to index those documents and update the versioning state accordingly.
So for reindex/backfill, we can have two modes:
- Full: Clear everything (index and versioning state) and then index all documents from source. This is like starting fresh.
- Backfill: Index documents for a specific range (or set of IDs) and update the versioning state for those documents.
Monitoring:
We can use a monitoring system like Prometheus to collect metrics from each service.
Metrics to collect:
Ingestion: records read, errors.
Preprocessing: duplicates removed, documents sent to indexing, processing time, errors.
Indexing: documents indexed, indexing latency, errors, index size.
Versioning storage: read/write latency, errors.
Alerts: on high error rates, low throughput, high latency, etc.
Implementation considerations:
The preprocessing service must be idempotent and exactly-once in processing. We can use message queue with at-least-once delivery and then make sure our versioning update is idempotent (using the document key and the hash and version). However, if we use the hash and version, we can detect if we have already processed a version for a key.
We might design the versioning storage to store for each document key:
current_version: integer
current_hash: string
is_deleted: boolean (or we can have a tombstone version that is marked as deleted)
When a new document comes:
If the key doesn't exist -> new document, version=1, index it.
If the key exists:
If the new hash == current_hash -> duplicate, skip.
If the new hash != current_hash and the document is not marked as deleted -> update: version = current_version+1, update hash, index the new document.
If the document is marked as deleted and current_version is not a tombstone -> create tombstone: version = current_version+1, mark as deleted, and then in indexing we remove the document (or mark as deleted in the index).
If the document is marked as deleted and current_version is already a tombstone -> skip (already deleted).
For indexing, we use the document key as the document ID. For a tombstone, we can either delete the document from the index or update it with a flag. It depends on the search engine.
For reindexing (full):
We can clear the index and the versioning state. Then we start fresh and index every document from the source as version 1 (or as the latest version if we have a version in the source). But note: if the source doesn't have version, we are generating version 1 for every document. Then when the next change comes, we will increment from 1.
Alternatively, if the source has a version (like a timestamp or a revision number) we can use that. But if we are generating our own version, then we start from 1.
For backfilling:
We read documents for a specific time range or set of keys. We process them as normal, but note that if the versioning state already has a higher version for a key, then we might skip? Or we might want to backfill and then the backfilled document might be an older version?
code
Reindex (full):
We clear the index and the versioning state. Then we read all documents from the source (with their versions) and process them as if they are new. This will set the versioning state to the latest version from the source and index the latest content.
Scalability:
- The preprocessing service can be scaled horizontally. We need to partition by document key so that the same key always goes to the same instance to avoid race conditions? Actually, we can use a distributed lock or use the storage that supports atomic compare-and-set for the versioning update. Alternatively, we can partition the key space and have each instance responsible for a set of keys.
code
- The indexing service can be scaled by having multiple consumers from the indexing queue.
Fault tolerance:
- The message queue (Kafka) provides durability and replay.
- The versioning storage must be durable and support atomic updates.
- We can have checkpoints in the ingestion and preprocessing to resume from failures.
Data formats:
- Documents in JSON or similar.
- The message queue messages can include the document and metadata (like source timestamp, version, etc.)
Example flow for a document update:
Source: Document with key "doc1", version 2, content "Hello World", hash = "abc123"
Preprocessing:
Look up "doc1" in versioning storage:
current_version = 1, current_hash = "abc123" (from previous version 1)
new_version (2) > current_version (1) -> proceed.
new_hash (abc123) == current_hash (abc123) -> same content, so update current_version to 2, skip indexing.
If the hash was different, then we would update current_version to 2, current_hash to new_hash, and send to indexing.
Example for deletion:
Source: Deletion marker for key "doc1", version 3.
Preprocessing:
current_version = 2, current_hash = "abc123"
new_version (3) > current_version (2) -> proceed.
It's a deletion -> update current_version to 3, set is_deleted to true, and send a deletion event to indexing.
Indexing: Delete the document with ID "doc1" from the index.
Example for backfill:
We missed version 2 of "doc1" (which was an update with new content and hash "def456"). Our current state is version 1 and hash "abc123".
We backfill version 2 with hash "def456".
Preprocessing:
current_version = 1, current_hash = "abc123"
new_version (2) > current_version (1) -> proceed.
new_hash (def456) != current_hash (abc123) -> update state and index.
Then later we get version 3 (deletion) as normal.
Example for full reindex:
We clear the index and the versioning state. Then we read all documents from the source (with their latest versions).
For "doc1", we read version 3 (deletion) and version 2 (update) and version 1 (original). But note: we only want the latest version? Actually, when reindexing from the source, we might get multiple versions. We should only index the latest version?
Let me know if you have any questions or need more details on a specific part.
I'll design a comprehensive search indexing pipeline with all the components you've requested. This is a production-grade system suitable for large-scale deployments.
class DeduplicationService:
def __init__(self, redis_client, postgres_client):
self.redis = redis_client # For hot dedup (TTL: 24h)
self.postgres = postgres_client # For persistent state
async def deduplicate_batch(self, documents: List[Document]) -> List[Document]:
"""Process batch with deduplication"""
unique_docs = []
for doc in documents:
# Generate content hash (SHA256 of normalized content)
content_hash = self._generate_hash(doc.content, doc.metadata)
doc_id = self._generate_doc_id(doc)
# Check Redis cache (fast path)
if await self.redis.exists(f"dedup:{content_hash}"):
continue
# Check PostgreSQL (persistent)
exists = await self.postgres.fetchval(
"SELECT 1 FROM dedup_index WHERE content_hash = $1",
content_hash
)
if not exists:
unique_docs.append(doc)
# Store in both systems
await self._store_hash(content_hash, doc_id)
return unique_docs
async def _store_hash(self, content_hash: str, doc_id: str):
"""Store hash in both Redis (cache) and PostgreSQL (source of truth)"""
# Redis with 24h TTL for hot cache
await self.redis.setex(f"dedup:{content_hash}", 86400, doc_id)
# PostgreSQL persistent storage
await self.postgres.execute(
"INSERT INTO dedup_index (content_hash, doc_id, first_seen) "
"VALUES ($1, $2, NOW()) ON CONFLICT DO NOTHING",
content_hash, doc_id
)
Database Schema for Deduplication
sql
CREATE TABLE dedup_index (
content_hash CHAR(64) PRIMARY KEY, -- SHA256
doc_id VARCHAR(255) NOT NULL,
first_seen TIMESTAMP DEFAULT NOW(),
source_metadata JSONB,
INDEX idx_first_seen (first_seen)
);
-- Partition by month for time-series queries
CREATE TABLE dedup_index_2024_01 PARTITION OF dedup_index
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
2. Versioning System
Document Version Management
python
class VersioningService:
def __init__(self, metadata_db):
self.db = metadata_db
async def get_latest_version(self, doc_id: str) -> Optional[DocumentVersion]:
"""Retrieve latest version for a document"""
return await self.db.fetchrow(
"SELECT * FROM document_versions "
"WHERE doc_id = $1 "
"ORDER BY version DESC LIMIT 1",
doc_id
)
async def create_version(
self,
doc_id: str,
content: str,
metadata: dict,
operation: str # 'CREATE', 'UPDATE', 'DELETE'
) -> DocumentVersion:
"""Create new version with optimistic locking"""
async with self.db.transaction():
latest = await self.get_latest_version(doc_id)
new_version = DocumentVersion(
doc_id=doc_id,
version=latest.version + 1 if latest else 1,
content_hash=self._hash_content(content),
content=content,
metadata=metadata,
operation=operation,
timestamp=datetime.utcnow(),
previous_hash=latest.content_hash if latest else None
)
# Check for concurrent modifications
if latest and new_version.previous_hash != latest.content_hash:
raise ConflictError("Document was modified concurrently")
await self.db.execute(
"INSERT INTO document_versions VALUES ($1, $2, $3, $4, $5, $6, $7)",
new_version.doc_id,
new_version.version,
new_version.content_hash,
new_version.content,
new_version.metadata,
new_version.operation,
new_version.timestamp
)
return new_version
Versioning Database Schema
sql
CREATE TABLE document_versions (
doc_id VARCHAR(255) NOT NULL,
version INTEGER NOT NULL,
content_hash CHAR(64) NOT NULL,
content TEXT NOT NULL,
metadata JSONB NOT NULL,
operation VARCHAR(20) NOT NULL, -- CREATE, UPDATE, DELETE
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (doc_id, version),
INDEX idx_doc_id_created (doc_id, created_at DESC)
);
-- Materialized view for latest versions (fast reads)
CREATE MATERIALIZED VIEW latest_document_versions AS
SELECT DISTINCT ON (doc_id) *
FROM document_versions
ORDER BY doc_id, version DESC;
CREATE UNIQUE INDEX idx_latest_doc_id ON latest_document_versions(doc_id);
3. Reindex/Backfill System
Reindex Orchestrator
python
class ReindexOrchestrator:
def __init__(self, config, kafka_producer, metadata_db):
self.config = config
self.kafka = kafka_producer
self.db = metadata_db
async def full_reindex(
self,
index_name: str,
batch_size: int = 1000,
start_date: Optional[datetime] = None
):
"""Complete reindex of all documents"""
# 1. Create new index with _reindex suffix
new_index = f"{index_name}_reindex_{int(time.time())}"
await self._create_index_with_mapping(new_index)
# 2. Stream all documents from source
query = "SELECT * FROM source_documents"
if start_date:
query += f" WHERE updated_at >= '{start_date}'"
async for batch in self._stream_batches(query, batch_size):
# 3. Send to processing pipeline
await self.kafka.send('indexing_queue', batch)
# 4. Wait for completion
await self._wait_for_completion(new_index)
# 5. Switch alias atomically
await self._switch_alias(index_name, new_index)
# 6. Cleanup old indices
await self._cleanup_old_indices(index_name)
async def backfill(
self,
index_name: str,
doc_ids: List[str],
since_version: Optional[int] = None
):
"""Backfill specific documents"""
backfill_index = f"{index_name}_backfill_{int(time.time())}"
for doc_id in doc_ids:
# Get all versions since specified version
versions = await self.db.fetch(
"SELECT * FROM document_versions "
"WHERE doc_id = $1 "
"AND version > $2 "
"ORDER BY version",
doc_id, since_version or 0
)
# Send each version in order
for version in versions:
if version.operation != 'DELETE':
await self.kafka.send('indexing_queue', {
'doc_id': doc_id,
'version': version.version,
'content': version.content,
'metadata': version.metadata,
'force_reindex': True
})
Checkpointing for Large Reindex
python
class CheckpointManager:
def __init__(self, redis_client):
self.redis = redis_client
async def save_checkpoint(
self,
job_id: str,
last_doc_id: str,
stats: dict
):
"""Save reindex progress"""
key = f"reindex:{job_id}"
await self.redis.hset(key, mapping={
'last_doc_id': last_doc_id,
'documents_processed': stats['processed'],
'documents_failed': stats['failed'],
'last_updated': datetime.utcnow().isoformat()
})
await self.redis.expire(key, 604800) # 7 days TTL
async def get_checkpoint(self, job_id: str) -> Optional[dict]:
"""Resume from checkpoint"""
key = f"reindex:{job_id}"
data = await self.redis.hgetall(key)
return data if data else None
Data Quality: Deduplication, versioning, validation
Would you like me to elaborate on any specific component or provide implementation details for a particular search engine (Elasticsearch vs OpenSearch vs Vespa)?
Actually, backfilling is typically for data that was missed. So we want to index the missed data and then versioning should work as if the data was processed in order. But if we are backfilling old data, then we might have a situation where the current state is already ahead. We need to decide:
Option 1: Backfill only misses that are before the current version? Then we would update the versioning state to the backfilled version if it's newer than the current? But if we are backfilling old data, it might be older.
Option 2: We backfill the missed data and then let the versioning state update only if the backfilled document is newer (by hash) than the current? This might be complex.
Alternatively, for backfill we might not update the versioning state? But then when the next change comes, we might reindex the same document again.
Let's think: if we missed a document that was updated at time T, and then later at T+1 there was another update. Our current state has the T+1 version. If we backfill the T version, we don't want to index it because we already have a newer version. So we should compare the hash of the backfilled document with the current hash. If they are the same, skip. If different and the backfilled document is older (by some timestamp) then we might still want to skip because we have a newer version? But what if the backfilled document is actually a correction?
This is getting complex. Perhaps we should have a timestamp on each document from the source and then in the versioning state we store the latest timestamp and hash. Then when backfilling, we only index if the backfilled document has a timestamp later than the current? But then if the source doesn't have a timestamp, we cannot do that.
Given the complexity, maybe we design the system such that:
- The source provides a monotonically increasing version (or timestamp) for each document. Then we can compare by that.
If the source does not provide a version, we can use the hash and the time we received the document? But that's not reliable for ordering.
Alternatively, we can design the pipeline to be resilient to out-of-order events by always taking the latest version (by hash) and ignoring older ones. But then if we backfill an older document that has a different hash, we would be overwriting the current with an older version? That might be undesirable.
So let's assume the source provides a reliable version (like a sequence number or a timestamp that increases with updates). Then:
In the versioning state, we store:
key -> (current_version, current_hash, is_deleted)
When a new document (from ingestion or backfill) arrives with version V:
If V <= current_version: skip (because we already have a newer version)
If V > current_version: then we update the state and index the document (or if it's a deletion, mark as deleted).
But note: what if we get a document with a higher version but the same hash? That could be a duplicate of a version we already have? Actually, if the hash is the same, then the content is the same, so we can skip even if the version is higher? But then we are skipping a version? We might break the versioning chain.
Alternatively, we might want to record every version? But in the index we only need the latest. So we can skip if the hash is the same as the current, regardless of the version? But then if the version is higher and the hash is the same, it's just a duplicate update?
Let's simplify:
We only care about the latest version of each document. So we store the latest version and its hash. When a new document comes:
If the document's version <= stored version: skip (we already have a newer or same version).
Else (document's version > stored version):
If the document's hash == stored hash: then it's a duplicate of the current content? But why would the version be higher and the same hash? Maybe the source re-sent the same version? We can skip and update the version? But the content didn't change. We might not need to index again, but we should update the version?
Actually, if the version is higher and the hash is the same, then it's the same content but with a higher version number. We might want to update the version in the state but skip indexing because the content is the same.
So:
if new_version <= current_version: skip.
else:
if new_hash == current_hash:
update current_version to new_version (and keep current_hash) -> skip indexing.
else:
update current_version to new_version, current_hash to new_hash, and index the new document.
And for deletions:
We treat a deletion as a document with a deletion marker and a version. We do the same version check, and if it's the latest, we mark as deleted in the state and then in the index we delete the document (or mark as deleted).
But note: if we have a deletion and then a new document with the same key but with a version after the deletion? That would be a recreation? We allow that because the version is higher.
Now, for backfilling, we use the same logic. We read the missed documents (with their versions from the source) and process them. If we have a current version that is higher, we skip. If the backfilled document has a higher version, we update and index.
But what if we are backfilling a range that is entirely before the current version? Then we skip everything? That might be okay because we already have newer versions.
However, if we are backfilling because we missed some documents that are actually the latest? Then we would have a gap. So we must ensure that we backfill the missed documents and that they have the correct version numbers relative to what we have.
This design relies on the source providing monotonically increasing versions for each document.
How do we know which is the latest? We rely on the version. So we might read all and then in the preprocessing we will process in the order of increasing version? But if we read all from the source, we might get them out of order.
We can sort by version during reindex? Or we can rely on the versioning logic: if we process in any order, the versioning state will update to the highest version we've seen. But if we process a lower version after a higher version, we will skip the lower version? That's what we want.
So during reindex, we can read all documents (with their versions) and send them to the preprocessing service in any order. The preprocessing service will only keep the highest version for each key.
But note: if we have a deletion at version 3 and then an update at version 4 (which recreates the document), then we want to have version 4 in the index. If we process version 3 (deletion) first and then version 4, that's fine. If we process version 4 first and then version 3, then when we process version 3 we will skip because version 3 < current_version (4). So we are safe.
So the reindex can be done by:
code
Step 1: Clear index and versioning state.
Step 2: Read all documents from the source (with their versions and deletion markers) and send them to the preprocessing service (or directly to indexing if we are sure we are only sending the latest?).
But note: we might have multiple versions for the same key in the source. We want only the latest. We can either:
code
a) Let the preprocessing service handle it by sending every version and letting the versioning state keep the highest.
b) Pre-aggregate in the reindex service to send only the latest version per key.
Option (a) is simpler and uses the same logic as normal operation.
Implementation steps:
a) Set up the versioning storage (table):
CREATE TABLE document_state (
key TEXT PRIMARY KEY,
current_version BIGINT,
current_hash TEXT,
is_deleted BOOLEAN
);
b) Preprocessing service (for each document):
code
-- Pseudocode for processing a document (with key, version, hash, is_deleted)
BEGIN TRANSACTION;
SELECT current_version, current_hash, is_deleted FROM document_state WHERE key = ? FOR UPDATE;
IF NOT FOUND THEN
-- New document
IF is_deleted THEN
-- We don't index a deletion for a new document? Actually, we can ignore because there's nothing to delete.
-- But we should store the state as deleted? Maybe we don't store a deletion for a non-existing document.
-- So: if it's a deletion and we don't have the document, then skip.
-- But what if we have a deletion and then later an update? We want to allow that.
-- So we store the deletion as the state? Then when an update comes with a higher version, we will index it.
-- So we do store the deletion.
INSERT INTO document_state (key, current_version, current_hash, is_deleted) VALUES (?, ?, ?, true);
-- Send deletion event to indexing? Actually, there's nothing to delete.
-- So we don't send anything to indexing for a deletion of a non-existing document? But then if we later get an update, we will index it and that's fine.
-- However, if we are reindexing and we get a deletion for a document that doesn't exist in the index? That's okay.
-- So we store the state but do not send an indexing event for the deletion of a non-existing document?
-- But what if the document was previously indexed and then we get a deletion? Then we would have indexed it and then we get a deletion -> we delete from index.
-- In this case, the document didn't exist before, so we don't have it in the index. So we skip sending to indexing.
ELSE
INSERT INTO document_state (key, current_version, current_hash, is_deleted) VALUES (?, ?, ?, false);
send_to_indexing(document);
END IF;
ELSE
-- We have a previous state
IF version <= current_version THEN
-- Skip: we already have a newer version.
-- But what if the version is the same? Then we might have a duplicate? We skip because the hash might be the same?
-- Actually, if the version is the same, then it's the same version from the source? We might have already processed it. We skip.
-- However, if the hash is different and the version is the same? That shouldn't happen because the source should not have two different contents for the same version. So we skip.
ELSE
-- version > current_version
IF is_deleted THEN
-- This is a deletion event.
UPDATE document_state SET current_version = ?, is_deleted = true WHERE key = ?;
-- Send deletion event to indexing only if the document was not already deleted?
-- But if the current state is not deleted, then we need to delete from index.
IF NOT current_is_deleted THEN
send_deletion_to_indexing(key);
END IF;
ELSE
-- It's an update or new document (if we are in the branch where we found a state, it's an update)
IF hash = current_hash THEN
-- Same content, just update the version.
UPDATE document_state SET current_version = ? WHERE key = ?;
-- Skip indexing because content is the same.
ELSE
-- New content
UPDATE document_state SET current_version = ?, current_hash = ?, is_deleted = false WHERE key = ?;
send_to_indexing(document);
END IF;
END IF;
END IF;
END IF;
COMMIT;
c) Indexing service:
- For a document: index it with the key as the document ID.
- For a deletion: delete the document by key.
d) Reindex service:
- Step 1: Truncate the index (or create a new index and switch alias).
- Step 2: Truncate the document_state table.
- Step 3: Read all documents from the source (with their versions and deletion markers) and send them to the preprocessing service (or directly to indexing? We want to use the same versioning logic to handle multiple versions). So we send to preprocessing.
code
However, note: when we truncate the state, we are starting fresh. Then we send every document (with its version) and the preprocessing will store the highest version for each key. But if we send multiple versions for the same key, the preprocessing will keep the highest. So we might send a lot of unnecessary data. We can pre-aggregate in the reindex service to send only the latest version per key? But then we are not testing the versioning logic?
Since we are truncating the state, we can send only the latest version per key. We can do:
SELECT key, MAX(version) as version, ... GROUP BY key.
But note: the source might not have a way to get the latest version per key? We might have to read all and aggregate.
Alternatively, we can read in chronological order and let the preprocessing handle it. But that would be inefficient.
So for reindex, we might want to pre-aggregate to the latest version per key and then send that to preprocessing. But then we are bypassing the versioning logic? Actually, we are still using the versioning logic to set the state to the latest version. But we are only sending one version per key, so the state will be set to that version. That's what we want.
However, what about deletions? If the latest version for a key is a deletion, then we want to mark it as deleted. So we need to include the deletion marker in the latest version.
So the reindex service can:
For each key, get the record with the highest version (and if there are multiple with the same version, take the one with the highest version? Actually, version should be unique per key? If not, we need to break ties).
But note: if we have a deletion at version 3 and then an update at version 4, then the latest version (4) is not a deletion. So we would index version 4. That's correct.
If we have an update at version 2 and then a deletion at version 3, then the latest version (3) is a deletion. So we would not index the document and mark as deleted.
So we can pre-aggregate by key to the latest version (by version number) and then send that to the preprocessing. This is efficient.
Steps for reindex:
1. For each key, get the record with the maximum version (and if there are multiple with the same max version, take the one that is not a deletion? Actually, if there are two with the same version, one is deletion and one is update? That shouldn't happen. But if it does, we can take the one that is not a deletion? Or the source should not have two records with the same version? We assume the source version is unique per key.
2. Then send these records to the preprocessing service. The preprocessing will then set the state and index accordingly.
But note: the preprocessing service will then update the state for each key with the version we send. Since we are sending the latest version, the state will be set to that version. And then we index the document if it's not a deletion.
e) Backfill service:
- Similar to reindex but for a subset (by time range or key range).
- We read the documents in that subset (with their versions) and send them to the preprocessing service.
- We do not truncate the state. The preprocessing will only update if the version is higher than the current.
Monitoring:
We can have each service expose metrics in a format that Prometheus can scrape.
We can also have a metric for the current size of the index and the versioning state.
Alerting:
We can set up alerts for:
- High error rates in any service.
- Low throughput (documents processed per second) compared to expected.
- High latency in preprocessing or indexing.
- The versioning storage size growing unexpectedly.
Dashboard:
We can use Grafana to create dashboards showing:
- Throughput of each stage.
- Error rates.
- Latency percentiles.
- Index size over time.
- Number of documents in the index vs. in the versioning state (should be the same for non-deleted documents).
Additional considerations:
Exactly-once processing: We are using at-least-once delivery from Kafka and idempotent updates in the preprocessing (using the version check). So we should be safe.
Ordering: We assume that for a given key, the versions are sent in order? Not necessarily. But our version check (if new_version > current_version) will ensure we only take newer versions. However, if we get an older version after a newer one, we skip. That's acceptable.
But what if we get a deletion (version 3) and then an update (version 4) and then the update (version 4) again? We will update the version to 4 again? But the hash might be the same? We skip indexing if the hash is the same. That's fine.
What if we get an update (version 4) and then a deletion (version 3)? Then the deletion will be skipped because version 3 < current_version (4). That's correct because the document is already at version 4 and then we try to delete an older version? That shouldn't happen if the source versions are monotonic. But if the source has a bug and sends an older deletion, we skip.
So the system is resilient to out-of-order events as long as the version numbers are monotonic per key.
If the source does not provide a version:
We cannot do the version check. Then we have to rely on the hash. But then if we get an update and then an older update (with a different hash) we would overwrite with the older? That's bad.
So we require the source to provide a monotonically increasing version per key.
If the source doesn't, we might use the timestamp of when we received the document? But that's not the same as the source version and might not be monotonic if we process out of order.
Alternatively, we can use the hash and the source timestamp (if available) and then in the versioning state we store the hash and the source timestamp. Then when a new document comes, we compare by source timestamp? But then if we get an older timestamp with a different hash, we would overwrite? That's the same problem.
So it's crucial to have a reliable monotonic version from the source.
Summary:
We have designed a pipeline that uses a version number (from the source) and a hash to detect changes and deduplicate. We store the latest version and hash for each key and only index if we get a newer version with a different hash.
We have services for ingestion, preprocessing (with versioning and dedup), indexing, and reindex/backfill.
We have monitoring for health and performance.
This design assumes the source provides a monotonic version per key.