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

Build

Five 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.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
  5. 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.

Which storage, files or records, then how they are reachedFor files, reached by key over HTTP by anyone, use object storage. Mounted as a disk by one machine, use block storage. Mounted by many machines as a shared filesystem, use file storage. For records that need joins, constraints and transactions, use a relational database. For simple lookups by key at very high scale or with a flexible schema, use a NoSQL store such as key-value or document.filesrecordsby key, over HTTPa disk for one VMa mount for manyyesno: lookups by key,huge scaleFiles or records?How are theyreached?Joins andtransactions?Object storageBlock storageFile storageRelational, SQLNoSQL: key-value,document
Which storage, files or records, then how they are reachedFor files, reached by key over HTTP by anyone, use object storage. Mounted as a disk by one machine, use block storage. Mounted by many machines as a shared filesystem, use file storage. For records that need joins, constraints and transactions, use a relational database. For simple lookups by key at very high scale or with a flexible schema, use a NoSQL store such as key-value or document.filesrecordsby key, over HTTPa disk for one VMa mount for manyyesno: lookups by key,huge scaleFiles or records?How are theyreached?Joins andtransactions?Object storageBlock storageFile storageRelational, SQLNoSQL: key-value,document
Which storage? Files or records, then how they are reached
KindAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
Object storageS3 (Simple Storage Service)Blob StorageCloud Storage
Block storageEBS (Elastic Block Store)Managed DisksPersistent Disk
File storageEFS (Elastic File System)Azure FilesFilestore
Managed relationalRDS (Relational Database Service), AuroraAzure SQL Database, Azure Database for PostgreSQLCloud SQL, AlloyDB, Spanner
Managed NoSQLDynamoDBCosmos DBFirestore, 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
}
Object storage from Java: put bytes under a key, then hand out a 15-minute download link
# 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"}}'
A read replica for reporting, and a key-value table billed per request
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);
}
Route read-only transactions to the replica; Spring decides before taking a connection
@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(); }
A read that must see the user's own write cannot go to a lagging replica
Replica lag, a write followed by a read that comes too soonThe app writes order 1042 to the primary, which commits and answers. The primary ships the change to the read replica asynchronously. A read sent to the replica before the change arrives finds nothing. A moment later the replica applies the change and the same read succeeds.Read replicaPrimaryorders appINSERT order 1042committedSELECT order 1042not found (lag)replicate the change, asyncSELECT order 1042found
Replica lag, a write followed by a read that comes too soonThe app writes order 1042 to the primary, which commits and answers. The primary ships the change to the read replica asynchronously. A read sent to the replica before the change arrives finds nothing. A moment later the replica applies the change and the same read succeeds.Read replicaPrimaryorders appINSERT order 1042committedSELECT order 1042not found (lag)replicate the change, asyncSELECT order 1042found
Replica lag: a write, then a read that comes too soon

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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());
}
Sign a 10-minute upload URL; the browser PUTs the file straight to the bucket

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

1. Three instances behind a load balancer must all serve the same user uploads. Where do the files go?
Show answers
  • Object storage, with the key saved in the database: Correct. Every instance reads the same bucket, and it survives scale-in.
  • A block volume attached to each instance: Incorrect. Each volume holds only what its own instance wrote.
  • Each instance's local disk, with sticky sessions: Incorrect. Files vanish with the instance and other users miss them.
2. A user places an order and is redirected to its confirmation page, which reads from a read replica. Sometimes it says "order not found". Why?
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.