Storage and managed databases
Mid-level Frequently asked 5 min
On this page
The question
What is the difference between object, block and file storage?
30-second answer
Object storage, such as S3 (Simple Storage Service), keeps whole objects under keys in a flat namespace, reached over HTTP: practically unlimited, durable across zones and cheap, but you replace objects rather than edit them in place. Block storage, such as EBS (Elastic Block Store), is a raw disk attached to one machine, formatted with a filesystem: lowest latency, for boot disks and self-run databases. File storage, such as EFS (Elastic File System), is a shared network filesystem that many machines mount at once.
Understand it
Pick the storage for each workload
BuildFive workloads need storage. Give each the kind that fits how it is read and written.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
- Empty
View as text
Five rows, one per workload, each with an empty slot for the storage that fits it. Five workloads need storage. Give each the kind that fits how it is read and written.
User photos, read by millions: Object: by key over HTTP, cheap. Data disk of one self-run database: Block: a raw disk for one VM. One folder mounted by 10 servers: File: a shared filesystem. Orders with joins and transactions: Relational: SQL and ACID. Carts by user ID, huge read rate: Key-value NoSQL: fast by key.
Bytes by key go to object storage, one machine’s disk is block, a shared mount is file, related records are relational, and huge key lookups go to key-value.
Five rows, one per workload, each with an empty slot for the storage that fits it. Five workloads need storage. Give each the kind that fits how it is read and written.
User photos, read by millions: Object: by key over HTTP, cheap. Data disk of one self-run database: Block: a raw disk for one VM. One folder mounted by 10 servers: File: a shared filesystem. Orders with joins and transactions: Relational: SQL and ACID. Carts by user ID, huge read rate: Key-value NoSQL: fast by key.
Bytes by key go to object storage, one machine’s disk is block, a shared mount is file, related records are relational, and huge key lookups go to key-value.
Takeaway: Choose storage by access pattern: object storage for files by key, block for one machine’s disk, file for a shared mount, relational for joins and transactions, key-value NoSQL for simple lookups at huge scale.
| Kind | AWS (Amazon Web Services) | Azure | GCP (Google Cloud Platform) |
|---|---|---|---|
| Object storage | S3 (Simple Storage Service) | Blob Storage | Cloud Storage |
| Block storage | EBS (Elastic Block Store) | Managed Disks | Persistent Disk |
| File storage | EFS (Elastic File System) | Azure Files | Filestore |
| Managed relational | RDS (Relational Database Service), Aurora | Azure SQL Database, Azure Database for PostgreSQL | Cloud SQL, AlloyDB, Spanner |
| Managed NoSQL | DynamoDB | Cosmos DB | Firestore, Bigtable |
In code
S3Client s3 = S3Client.create();
s3.putObject(PutObjectRequest.builder()
.bucket("acme-photos")
.key("users/42/avatar.jpg")
.contentType("image/jpeg")
.build(),
RequestBody.fromFile(Path.of("avatar.jpg")));
try (S3Presigner presigner = S3Presigner.create()) {
PresignedGetObjectRequest link = presigner.presignGetObject(GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(15))
.getObjectRequest(get -> get.bucket("acme-photos").key("users/42/avatar.jpg"))
.build());
System.out.println(link.url()); // anyone with this URL can read the object until it expires
}# Asynchronous copy of the primary: reads scale out, writes still go to the primary
aws rds create-db-instance-read-replica \
--db-instance-identifier orders-db-reports \
--source-db-instance-identifier orders-db
# Key-value: one partition key, no schema beyond it, capacity billed per request
aws dynamodb create-table --table-name carts \
--attribute-definitions AttributeName=userId,AttributeType=S \
--key-schema AttributeName=userId,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
aws dynamodb get-item --table-name carts --key '{"userId": {"S": "42"}}'class ReplicaRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly() ? "replica" : "primary";
}
}
@Bean
DataSource dataSource(DataSource primary, DataSource replica) {
var routing = new ReplicaRoutingDataSource();
routing.setTargetDataSources(Map.of("primary", primary, "replica", replica));
routing.setDefaultTargetDataSource(primary);
routing.afterPropertiesSet();
// Lazy: the connection is fetched at the first query, once the read-only flag is known
return new LazyConnectionDataSourceProxy(routing);
}@Transactional
public long place(Order order) { return orders.save(order).getId(); }
// Wrong: read-only goes to the replica, which may be a second behind: "order not found"
Wrong @Transactional(readOnly = true)
Wrong public Order confirmation(long id) { return orders.findById(id).orElseThrow(); }
// Right: read your own writes from the primary; send reports and searches to the replica
Right @Transactional
Right public Order confirmationAfterPlacing(long id) { return orders.findById(id).orElseThrow(); }Solve it
Design the storage for photo uploads of up to 20 MB
A Spring Boot service on three instances lets users upload photos of up to 20 MB, shows them as thumbnails in a feed, and
keeps each photo’s owner, caption, tags and likes. The first draft stores files in /var/uploads on the instance that
received them and the metadata in PostgreSQL. Uploads time out under load, and half the feed shows broken images. Redesign it.
- Find why images break. Each file sits on one instance’s disk, but the load balancer sends reads anywhere, so two of three instances return 404. Local disks are also lost on scale-in. Files must leave the instances.
- Split bytes from metadata. Photos go to object storage under a key such as
photos/{userId}/{uuid}.jpg; owner, caption, tags and likes stay in PostgreSQL, which handles the feed’s queries and joins, with the key as a column. - Keep 20 MB off the app servers. The service returns a presigned upload URL, and the browser sends the file straight to the bucket. Instances only sign URLs and save metadata, so uploads no longer tie up their threads.
- Serve and shrink. An event on each new object triggers a function that writes thumbnails; a CDN (content delivery network) serves them near users. A lifecycle rule moves originals to a cheaper storage class after 90 days.
- Check. Kill an instance during uploads and reload the feed: every image still loads. Load-test uploads and watch the instances’ CPU stay flat while the bucket absorbs the traffic.
public PhotoUpload startUpload(long userId, String contentType) {
String key = "photos/%d/%s.jpg".formatted(userId, UUID.randomUUID());
PresignedPutObjectRequest upload = presigner.presignPutObject(PutObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(10))
.putObjectRequest(put -> put.bucket("acme-photos").key(key).contentType(contentType))
.build());
photos.save(new Photo(userId, key, PhotoStatus.UPLOADING)); // metadata in PostgreSQL
return new PhotoUpload(key, upload.url().toString());
}How to answer
- Object storage fits uploads, backups, logs, static sites and data lakes.
- A block volume lives in one zone and attaches to one VM (virtual machine) at a time, as a rule.
- File storage fits legacy apps that need a shared POSIX directory, at a higher price.
- Cost and throughput differ by tier, such as standard against archive classes, or IOPS (input/output operations per second) for disks.
Common mistakes
- Storing user uploads on an instance's local disk behind a load balancer.
- Mounting object storage as if it were a POSIX filesystem for a database.
Follow-up questions
When would you choose a NoSQL database over a relational one?
Relational databases give a schema, joins, constraints and ACID (atomicity, consistency, isolation, durability) transactions, and answer queries nobody planned; they are the right default for business data such as orders and accounts. I choose NoSQL when the access pattern is known and simple, such as reading a cart or a session by key, at a scale or latency where one relational primary struggles, or when the data is naturally a document or a time series. You design NoSQL tables around queries, not entities.
- Key-value and document stores scale horizontally by partition key.
- A bad partition key creates hot partitions that throttle.
- Many systems use both, such as PostgreSQL for orders and DynamoDB or Redis for carts.
See it in the infographic: Pick the storage for each workload
What are read replicas, and what do you have to watch out for?
Read replicas are copies of a primary database that receive its changes asynchronously and serve read-only queries, so reads scale out while all writes still go to the primary. They suit reports, searches and read-heavy pages. The catch is replica lag: a replica may be seconds behind, so a user who just wrote may not see their own change. Route reads that need fresh data to the primary, and monitor lag.
- Replicas scale reads, not writes; writes need a bigger primary, sharding or another store.
- In Spring, route readOnly transactions with a routing data source behind a lazy connection proxy.
- A replica can be promoted on failover, but with asynchronous lag it may lose the last writes.
See it in the infographic: Pick the storage for each workload
What does a managed database such as RDS give you, and what stays your job?
RDS (Relational Database Service) and its equivalents run the hardware, install and patch the engine, take automated backups with point-in-time recovery, replace failed hosts, fail over to a standby in another zone and add read replicas on request. You still design the schema and indexes, tune queries, size the instance and connections, choose the maintenance window, control network access and users, encrypt data, and test restores.
- Point-in-time recovery restores to any second in the retention window.
- A restore creates a new instance, so the app needs a new endpoint or a DNS (Domain Name System) switch.
- Slow queries remain your problem on any managed service.
See it in the infographic: Pick the storage for each workload
Why does a disk fail to follow an instance into another availability zone?
A block volume is replicated only inside its own zone, which keeps its latency low. To use the data in another zone, take a snapshot, which is stored regionally, and create a new volume from it there. That is why stateful workloads on Kubernetes stay pinned to the zone of their volume.
Check yourself
Show answers
- The replica has not yet received the write: Correct. Replication is asynchronous; read your own writes from the primary.
- The replica has a different schema: Incorrect. A replica copies the primary's schema exactly.
- The browser cached an old page: Incorrect. The page is new; the data behind it is what lags.