Object storage & search indexes
Know when to put data in blob storage or a search engine instead of a database.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
Databases are poor at storing large files and at full-text search. Object storage like S3 holds blobs cheaply and durably, while search engines like Elasticsearch use inverted indexes to find documents by words fast.
Explained simply
Databases are great at small, structured records like users and orders. They are poor at two other jobs: holding huge files and finding text by its words. Each job has its own specialised tool.
Object storage, such as Amazon S3, Google Cloud Storage or Cloudflare R2, is like a giant warehouse of labelled boxes. You put a file in under a name, called a key, and fetch it later by that name. It is cheap, almost never loses data and has no practical size limit.
A search engine, such as Elasticsearch, OpenSearch or Meilisearch, works like the index at the back of a book: each word points to the pages that contain it. It can find "red running shoes" among millions of products in milliseconds and put the best matches first.
The database stays the source of truth. Object storage holds the bytes of files, and the database stores their keys. The search index is a copy built purely for finding things, so if it is ever lost, you rebuild it from the database.
Press Play on a diagram to walk through it one step at a time.
- 1Write to database
Database stays the source of truth
- 2Change event
CDC or outbox emits the change
- 3Queue or stream
Kafka buffers change events
- 4Indexer
Transforms rows into search documents
- 5Search index
Elasticsearch serves text queries
- Structured records
- Transactions and joins
- Exact lookups by key
- Small values
- Images, video, backups
- Cheap, highly durable
- Access by key over HTTP
- Pair with a CDN
- Full-text and fuzzy search
- Relevance ranking
- Faceted filters
- Derived, rebuildable copy
- Client to API server: I want to upload cat.jpg (2 MB)1I want to upload cat.jpg (2 MB)
- API server to Client: Presigned PUT URL, valid 15 min2Presigned PUT URL, valid 15 min
- Client to Object storage: PUT file bytes directly3PUT file bytes directly
- Object storage to Client: 200 OK4200 OK
- Client to API server: Upload done: photos/u42/cat.jpg5Upload done: photos/u42/cat.jpg
- API server to Database: Save photo record with key6Save photo record with key
- 1Raw text
"Running Shoes for Men!"
- 2Tokenise
Running, Shoes, for, Men
- 3Lowercase
running, shoes, for, men
- 4Drop stop words
running, shoes, men
- 5Stem
run, shoe, men
- 6Index
Each word → list of matching documents
In depth
How object storage stays safe and cheap
Amazon S3 is designed for 99.999999999 percent (eleven nines) durability. It achieves this by spreading each object across several facilities, using copies or erasure coding, which splits a file into data and parity pieces so it can be rebuilt even if some pieces are lost.
The namespace is flat. "photos/2024/cat.jpg" is just one key; the slashes only look like folders. Cost has three parts: gigabytes stored per month, number of requests, and data downloaded to the internet. Storage classes such as Standard, Infrequent Access and Glacier trade cheaper storage for slower or pricier access, and lifecycle rules move old objects between them automatically.
Uploading big files the right way
Sending a 2 GB video through your app servers wastes their bandwidth and memory. Instead, the app hands the client a presigned URL, a link that allows one upload to one key for a limited time, and the client sends the bytes straight to storage.
Large files use multipart upload. The file is split into parts of 5 MB to 5 GB, up to 10,000 parts, which upload in parallel and can be retried one by one if the network drops. S3 objects can be up to 5 TB. When the upload finishes, an event notification can trigger processing, such as creating thumbnails. Store the object key in your database and generate download URLs when needed.
- 1Get presigned URLs
From your API, time limited
- 2Split the file
Parts of 5 MB to 5 GB, up to 10,000
- 3Upload in parallel
Straight to storage
- 4Retry failed parts
Only the parts that dropped
- 5Complete
Event can trigger thumbnails
What happens to text before it is indexed
Before indexing, a search engine runs each text field through an analyzer. It splits text into tokens, lowercases them, often removes very common stop words such as "the" and "for", and may stem words so "running" and "runs" both become "run". Synonym rules can make "sneakers" match "shoes".
The same analyzer runs on the user's query, so both sides end up in the same form and match. Results are then ranked, usually with BM25, which gives more weight to rare words and to matches in short fields such as a title.
Shards, replicas and refresh
An Elasticsearch index is split into primary shards, each a self-contained Lucene index that can live on a different machine. Replica shards are copies that serve reads and take over if a node fails. Elastic's guidance is to keep shards roughly between 10 and 50 GB.
Search is near real-time, not instant. New documents become searchable after a refresh, which happens every second by default. Some changes, such as changing how a field is analysed, need a full reindex. The safe way is to build a new index, then point an alias, a stable name your app queries, at it in one atomic step.
- 1App queries an alias
e.g. products points at products_v1
- 2Create products_v2
With the new analysis settings
- 3Reindex documents
Fill v2 from the source data
- 4Swap the alias
One atomic step to v2
- 5Drop products_v1
Once v2 looks right
When you do not need a search engine
A separate search cluster is one more system to run, secure and keep in sync. PostgreSQL has solid built-in full-text search: a tsvector column holds the processed words, a GIN index makes lookups fast, and ts_rank orders results. The pg_trgm extension adds fuzzy matching and speeds up LIKE queries. This comfortably handles millions of rows for many apps.
Reach for Elasticsearch or OpenSearch when you need advanced relevance tuning, typo tolerance, faceted filters across huge catalogues, or when search traffic would put too much load on your main database.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Store large blobs in object storage~40m
- 2Use an inverted index for search~40m
- 3Keep a search index in sync with the database~40m
Key points
- Store blobs in object storage and only their URLs or keys in the database.
- Let clients upload directly to object storage with pre-signed URLs.
- An inverted index maps each word to the documents containing it.
- Search indexes are eventually consistent copies, never the source of truth.
Key terms
Tap a card to flip it. 0/5 known
Examples
Full-text search in PostgreSQL first
Step 1: add a generated tsvector column that combines the product name and description, analysed with English rules. Step 2: add a GIN index on it. Step 3: turn the user's text into a query with websearch_to_tsquery, which understands quotes and minus signs like a web search box. Step 4: filter with @@ and sort by ts_rank. For many shops this is all the search they need.
ALTER TABLE products ADD COLUMN search tsvector
GENERATED ALWAYS AS (
to_tsvector('english', name || ' ' || coalesce(description, ''))
) STORED;
CREATE INDEX products_search_idx ON products USING GIN (search);
SELECT id, name, ts_rank(search, q) AS rank
FROM products, websearch_to_tsquery('english', 'red running shoes') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;Reindexing with zero downtime
You want to add synonyms to the product index, which needs a reindex. Step 1: create products_v2 with the new settings. Step 2: bulk-load it from the database, the source of truth. Step 3: replay changes that happened during the load from the change stream. Step 4: compare document counts and run sample queries. Step 5: switch the alias "products" from v1 to v2 in one atomic call. The app always queries "products", so users never notice. Keep v1 for a day in case you need to roll back.
POST /_aliases
{
"actions": [
{ "remove": { "index": "products_v1", "alias": "products" } },
{ "add": { "index": "products_v2", "alias": "products" } }
]
}Quick reference
- Files go in object storage; the database keeps only the key and metadata
- S3 multipart: parts of 5 MB–5 GB, up to 10,000 parts, objects up to 5 TB
- Lifecycle rules move old objects to cheaper storage classes automatically
- Use the same analyzer for indexing and for queries, or words will not match
- Elasticsearch shards: aim for roughly 10–50 GB each
- New documents are searchable after a refresh, about 1 s by default
- Query through an alias so you can reindex and switch with no downtime
- PostgreSQL tsvector + GIN index is enough search for many apps
Common mistakes
- Storing images as BLOBs inside the relational database.
- Dual-writing to DB and search index from the app without retries.
- Treating the search engine as the primary data store.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Decide where each belongs (database, object storage or search index): a profile photo, a user's email address, product descriptions users search through, a nightly database backup, order rows.
- Exercise 2medium
Design a presigned upload flow for profile photos up to 5 MB, JPEG or PNG only. Say what the API checks, what the URL allows and what the database stores.
- Exercise 3hard
Keep a product search index in sync with PostgreSQL for 10 million products and about 200 updates per second. Changes must be searchable within 5 seconds, and an indexer crash must not lose or reorder updates.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I store images inside my database?
- You can, but it bloats backups, slows replication and costs more than object storage. Store the image in S3 or similar and keep its key in the database.
- Is Elasticsearch a database?
- It stores data, but treat it as a search copy rather than the source of truth. It lacks the transactions and strong guarantees that a primary database provides.
- Is object storage the same as a file server?
- No. Object storage is accessed over HTTP by key, cannot edit part of a file in place, and scales almost without limit. A file server offers folders and in-place edits but is much harder to scale.