Polski

Tutorial · AWS S3

AWS S3 in practice – browser uploads, presigned URLs, multipart, CloudFront and costs (Node.js, C#, Python)

We store pierogi photos and invoices in Amazon S3 with the AWS SDK for JavaScript v3 – a bucket with safe defaults, a least-privilege IAM policy, browser uploads via presigned POST, downloads via short-lived links and streaming, multipart for large files, CloudFront with Origin Access Control, lifecycle rules and costs. Variants in C# (AWSSDK.S3) and Python (boto3).

By · · 26 min read

Halina's pierogi shop got a new admin panel: the cook takes a photo of the pierogi with a phone and adds it to the menu, a customer downloads an invoice, and every night the system saves an order export. All these files go to Amazon S3. I will show you how to do it so that the API server does not push megabytes through itself, the bucket is not public, and the end-of-month bill holds no surprises.

Prerequisites: an AWS account with console access and AWS CLI v2 (signing in via aws configure sso or a profile), Node.js 22+, Express basics (Express tutorial). For the variants: .NET 10 SDK or Python 3.10+.

11 nines
of designed durability – 99.999999999% over a year
5 GB
max single PUT – larger files only via multipart
10,000
parts per multipart upload – each from 5 MiB to 5 GiB
1,000
keys per list page – pagination beyond that
Diagram: Architecture: who talks to whom and with which permissions

Step 1. Buckets with safe settings

We create two buckets: media for menu photos (public, but only through CloudFront) and private for invoices and exports. Names are globally unique, so we append the account number.

REGION=eu-central-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
for B in pierogi-media-$ACCOUNT pierogi-private-$ACCOUNT; do
  aws s3api create-bucket --bucket $B --region $REGION \
    --create-bucket-configuration LocationConstraint=$REGION
done
aws s3api put-bucket-cors --bucket pierogi-media-$ACCOUNT --cors-configuration file://infra/bucket-cors.json
aws s3api put-bucket-lifecycle-configuration --bucket pierogi-private-$ACCOUNT --lifecycle-configuration file://infra/lifecycle.json
aws s3api put-bucket-versioning --bucket pierogi-private-$ACCOUNT --versioning-configuration Status=Enabled

The good news: since 2023 new buckets have Block Public Access on, ACLs disabled (Object Ownership = Bucket owner enforced) and SSE-S3 encryption of every object by default. Do not turn these settings off – a public bucket is still one of the most common causes of data leaks. Versioning on the invoice bucket protects against accidental overwrites and deletes. Since December 2020 S3 also provides strong consistency: right after a successful write every read and listing sees the new object.

Step 2. The project and S3 clients

npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner @aws-sdk/s3-presigned-post @aws-sdk/lib-storage @aws-sdk/cloudfront-signer express zod

Configuration and S3 clients (Node.js)

package.json
{
  "name": "pierogi-s3",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=22.12" },
  "scripts": {
    "dev": "tsx watch --env-file-if-exists=.env src/server.ts",
    "build": "tsc -p tsconfig.build.json",
    "start": "node --env-file-if-exists=.env dist/server.js",
    "typecheck": "tsc --noEmit"
  },
  "dependencies": {
    "@aws-sdk/client-s3": "^3.1178.0",
    "@aws-sdk/cloudfront-signer": "^3.1177.0",
    "@aws-sdk/lib-storage": "^3.1178.0",
    "@aws-sdk/s3-presigned-post": "^3.1178.0",
    "@aws-sdk/s3-request-presigner": "^3.1178.0",
    "express": "^5.3.0",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/express": "^5.0.6",
    "@types/node": "^24.19.4",
    "tsx": "^4.23.15",
    "typescript": "^7.0.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "web"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "noEmit": false, "rootDir": "src", "outDir": "dist" },
  "include": ["src"]
}
.env.example
PORT=3000
AWS_REGION=eu-central-1
MEDIA_BUCKET=pierogi-media-123456789012
PRIVATE_BUCKET=pierogi-private-123456789012
CDN_URL=https://d111111abcdef8.cloudfront.net
MAX_PHOTO_BYTES=5242880
# Local development with LocalStack: S3_ENDPOINT=http://localhost:4566
# Credentials come from `aws configure sso` / AWS_PROFILE – never put keys here.
src/config.ts
import { z } from 'zod';

const EnvSchema = z.object({
  PORT: z.coerce.number().int().default(3000),
  AWS_REGION: z.string().default('eu-central-1'),
  // Public menu photos (served through CloudFront) and private documents.
  MEDIA_BUCKET: z.string().min(3),
  PRIVATE_BUCKET: z.string().min(3),
  CDN_URL: z.url(), // e.g. https://d111111abcdef8.cloudfront.net
  MAX_PHOTO_BYTES: z.coerce.number().int().positive().default(5 * 1024 * 1024),
  // Only for LocalStack/MinIO in development – leave empty in AWS.
  S3_ENDPOINT: z.url().optional(),
});

export type Config = z.infer<typeof EnvSchema>;
export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => EnvSchema.parse(env);
src/s3.ts
import { S3Client } from '@aws-sdk/client-s3';
import type { Config } from './config.js';

// No credentials in code: the default provider chain finds them
// (AWS_PROFILE / env vars locally, the IAM role on ECS, Lambda or EC2).
export function createS3Clients(config: Config) {
  const common = {
    region: config.AWS_REGION,
    ...(config.S3_ENDPOINT ? { endpoint: config.S3_ENDPOINT, forcePathStyle: true } : {}),
  };
  return {
    // Regular client: SDK-side integrity checksums stay on (default since v3.729).
    s3: new S3Client(common),
    // Client for presigned URLs used by browsers: no checksum of an empty body baked into the URL.
    presigner: new S3Client({ ...common, requestChecksumCalculation: 'WHEN_REQUIRED' }),
  };
}

export type S3Clients = ReturnType<typeof createS3Clients>;

AWS SDK v3 is modular: you install only the service client (@aws-sdk/client-s3) and the tools you need, and every operation is a command object sent with client.send(). A client is expensive to create (connection pool, credential lookup) – create it once and share it.

Why two clients? Since version 3.729 the SDK computes CRC32 checksums for uploaded data by default. For regular server-side uploads that is a plus. But in a presigned PUT URL for a browser the SDK puts an x-amz-checksum-crc32 computed from… an empty body into the address – I verified this on version 3.1178. The browser sends the real file, the checksum does not match, and S3 rejects the upload. A client with requestChecksumCalculation: 'WHEN_REQUIRED' used only for signing solves the problem without disabling integrity protection for other operations.

Step 3. IAM: the least privilege possible

The app's role gets exactly what it needs, and only within its prefixes.

App role IAM policy and bucket CORS

infra/iam-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "MenuPhotos",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::pierogi-media-123456789012/menu/*"
    },
    {
      "Sid": "Invoices",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:GetObject"],
      "Resource": "arn:aws:s3:::pierogi-private-123456789012/invoices/*"
    },
    {
      "Sid": "Exports",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:AbortMultipartUpload"],
      "Resource": "arn:aws:s3:::pierogi-private-123456789012/exports/*"
    },
    {
      "Sid": "ListExportsOnly",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::pierogi-private-123456789012",
      "Condition": { "StringLike": { "s3:prefix": ["exports/*"] } }
    }
  ]
}
infra/bucket-cors.json
{
  "CORSRules": [
    {
      "AllowedOrigins": ["https://admin.pierogarnia.example", "http://localhost:5173"],
      "AllowedMethods": ["POST", "PUT"],
      "AllowedHeaders": ["*"],
      "ExposeHeaders": ["ETag"],
      "MaxAgeSeconds": 3000
    }
  ]
}
  • A presigned URL carries the permissions of whoever signed it. The API role needs s3:PutObject on menu/*, otherwise signed forms are rejected. There is no separate "signing" permission.
  • HeadObject requires s3:GetObject, listing requires s3:ListBucket on the bucket (not on objects), narrowed with an s3:prefix condition.
  • s3:AbortMultipartUpload lets the SDK clean up after a failed multipart upload.
  • CORS is needed because the browser sends the form from the panel's domain to the S3 domain. Only specific origins and methods – no *.

Step 4. Browser uploads: presigned POST

The worst way to upload is to push the file through the API: the server holds someone else's megabytes in memory, you pay for the transfer twice, and Express's body limit has to be raised to absurd levels. Better: the API signs a form and the browser sends the file directly to S3.

Diagram: Uploading a dish photo via presigned POST

Signed upload and verification (Node.js, C#, Python)

src/photos.ts
import { randomUUID } from 'node:crypto';
import { DeleteObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import type { Config } from './config.js';
import type { S3Clients } from './s3.js';

const EXTENSIONS: Record<string, string> = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp' };

export class UploadError extends Error {}

// Step 1: the API signs an upload; the browser sends the file straight to S3.
export async function createPhotoUpload({ presigner }: S3Clients, config: Config, dishId: string, contentType: string) {
  const ext = EXTENSIONS[contentType];
  if (!ext) throw new UploadError(`Unsupported type ${contentType}`);
  // Our own key – never the user's file name (path tricks, collisions, PII in URLs).
  const key = `menu/${dishId}/${randomUUID()}.${ext}`;
  const { url, fields } = await createPresignedPost(presigner, {
    Bucket: config.MEDIA_BUCKET,
    Key: key,
    // S3 itself rejects files that are too big – something a presigned PUT cannot enforce.
    Conditions: [['content-length-range', 1, config.MAX_PHOTO_BYTES]],
    // Every field below becomes an exact-match condition of the signed policy.
    Fields: { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=31536000, immutable' },
    Expires: 300, // seconds
  });
  return { url, fields, key };
}

// Step 2: the browser reports the key; we check what really landed in S3.
export async function confirmPhoto({ s3 }: S3Clients, config: Config, dishId: string, key: string) {
  if (!key.startsWith(`menu/${dishId}/`)) throw new UploadError('Key does not belong to this dish');
  const head = await s3.send(new HeadObjectCommand({ Bucket: config.MEDIA_BUCKET, Key: key }));
  if (!head.ContentType || !(head.ContentType in EXTENSIONS) || (head.ContentLength ?? 0) > config.MAX_PHOTO_BYTES) {
    await s3.send(new DeleteObjectCommand({ Bucket: config.MEDIA_BUCKET, Key: key }));
    throw new UploadError('Uploaded file rejected');
  }
  return { key, size: head.ContentLength, url: `${config.CDN_URL}/${key}` };
}
dotnet/S3Demo/PhotoUploads.cs
using Amazon.S3;
using Amazon.S3.Model;

namespace S3Demo;

public sealed record PhotoUpload(string Url, IDictionary<string, string> Fields, string Key);

public sealed class PhotoUploads(IAmazonS3 s3, string bucket, long maxBytes)
{
    private static readonly Dictionary<string, string> Extensions = new()
    {
        ["image/jpeg"] = "jpg",
        ["image/png"] = "png",
        ["image/webp"] = "webp",
    };

    // Presigned POST: S3 enforces the size range and the content type itself.
    public async Task<PhotoUpload> CreateAsync(string dishId, string contentType)
    {
        if (!Extensions.TryGetValue(contentType, out var ext))
            throw new ArgumentException($"Unsupported type {contentType}");

        var key = $"menu/{dishId}/{Guid.NewGuid()}.{ext}";
        var response = await s3.CreatePresignedPostAsync(new CreatePresignedPostRequest
        {
            BucketName = bucket,
            Key = key,
            Expires = DateTime.UtcNow.AddMinutes(5),
            Conditions =
            [
                S3PostCondition.ContentLengthRange(1, maxBytes),
                S3PostCondition.ExactMatch("Content-Type", contentType),
            ],
            Fields = new Dictionary<string, string> { ["Content-Type"] = contentType },
        });
        return new PhotoUpload(response.Url, response.Fields, key);
    }

    // After the browser reports success: check what really landed in the bucket.
    public async Task<long> ConfirmAsync(string dishId, string key)
    {
        if (!key.StartsWith($"menu/{dishId}/", StringComparison.Ordinal))
            throw new ArgumentException("Key does not belong to this dish");
        var head = await s3.GetObjectMetadataAsync(bucket, key);
        if (head.ContentLength > maxBytes || !Extensions.ContainsKey(head.Headers.ContentType ?? ""))
        {
            await s3.DeleteObjectAsync(bucket, key);
            throw new InvalidOperationException("Uploaded file rejected");
        }
        return head.ContentLength;
    }
}
python/photo_uploads.py
import uuid

from s3_client import MEDIA_BUCKET, s3

EXTENSIONS = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp"}
MAX_BYTES = 5 * 1024 * 1024


def create_photo_upload(dish_id: str, content_type: str) -> dict:
    """Presigned POST: S3 itself enforces the size range and the content type."""
    ext = EXTENSIONS.get(content_type)
    if ext is None:
        raise ValueError(f"Unsupported type {content_type}")
    key = f"menu/{dish_id}/{uuid.uuid4()}.{ext}"
    post = s3.generate_presigned_post(
        Bucket=MEDIA_BUCKET,
        Key=key,
        Fields={"Content-Type": content_type},
        Conditions=[
            ["content-length-range", 1, MAX_BYTES],
            {"Content-Type": content_type},
        ],
        ExpiresIn=300,
    )
    return {"url": post["url"], "fields": post["fields"], "key": key}


def confirm_photo(dish_id: str, key: str) -> int:
    """Check what really landed in S3 before saving the key in the database."""
    if not key.startswith(f"menu/{dish_id}/"):
        raise ValueError("Key does not belong to this dish")
    head = s3.head_object(Bucket=MEDIA_BUCKET, Key=key)
    if head["ContentLength"] > MAX_BYTES or head.get("ContentType") not in EXTENSIONS:
        s3.delete_object(Bucket=MEDIA_BUCKET, Key=key)
        raise ValueError("Uploaded file rejected")
    return head["ContentLength"]
Presigned PUTPresigned POST
CallgetSignedUrl(client, new PutObjectCommand(...))createPresignedPost(client, { Conditions })
Size limitnone – the client can send up to 5 GBcontent-length-range in the policy
File typeContent-Type unsigned unless you add it to signableHeadersexact match or starts-with
In the browserfetch(url, { method: 'PUT', body: file })FormData with fields and the file last
Whenuploads from trusted servers, CLI toolsuploads from users

Verification after the upload (confirmPhoto) is mandatory: the browser could report another dish's key, and the policy does not check whether the file really is an image. For full protection add scanning (e.g. Amazon GuardDuty Malware Protection for S3) or image processing in a Lambda triggered by the s3:ObjectCreated event that stores a safe, resized copy.

Step 5. The browser and API routes

Browser function and Express server

web/upload-photo.ts
// Browser side: ask the API for a signed form, then POST the file directly to S3.
export async function uploadDishPhoto(dishId: string, file: File, accessToken: string): Promise<string> {
  const headers = { 'content-type': 'application/json', authorization: `Bearer ${accessToken}` };
  const signed = await fetch(`/api/dishes/${dishId}/photo-uploads`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ contentType: file.type }),
  });
  if (!signed.ok) throw new Error(`Cannot start upload: ${signed.status}`);
  const { url, fields, key } = (await signed.json()) as { url: string; fields: Record<string, string>; key: string };

  const form = new FormData();
  for (const [name, value] of Object.entries(fields)) form.append(name, value);
  form.append('file', file); // the file must be the LAST field of the form

  const uploaded = await fetch(url, { method: 'POST', body: form });
  // 204 = stored; 403 with EntityTooLarge / policy errors comes back as XML.
  if (!uploaded.ok) throw new Error(`S3 rejected the file: ${uploaded.status} ${await uploaded.text()}`);

  const confirmed = await fetch(`/api/dishes/${dishId}/photo`, { method: 'PUT', headers, body: JSON.stringify({ key }) });
  if (!confirmed.ok) throw new Error(`Upload not accepted: ${confirmed.status}`);
  return ((await confirmed.json()) as { url: string }).url;
}
src/server.ts
import { pipeline } from 'node:stream/promises';
import express, { type ErrorRequestHandler } from 'express';
import { z } from 'zod';
import { loadConfig } from './config.js';
import { invoiceDownloadUrl, openInvoice } from './invoices.js';
import { confirmPhoto, createPhotoUpload, UploadError } from './photos.js';
import { createS3Clients } from './s3.js';

const config = loadConfig();
const clients = createS3Clients(config);
const app = express();
app.use(express.json());

// In a real app these routes sit behind authentication and authorization (staff / order owner).
app.post('/api/dishes/:dishId/photo-uploads', async (req, res) => {
  const { contentType } = z.object({ contentType: z.string() }).parse(req.body);
  res.status(201).json(await createPhotoUpload(clients, config, req.params.dishId, contentType));
});

app.put('/api/dishes/:dishId/photo', async (req, res) => {
  const { key } = z.object({ key: z.string() }).parse(req.body);
  res.json(await confirmPhoto(clients, config, req.params.dishId, key));
});

app.get('/api/orders/:orderId/invoice', async (req, res) => {
  res.redirect(302, await invoiceDownloadUrl(clients, config, req.params.orderId));
});

app.get('/api/orders/:orderId/invoice/stream', async (req, res) => {
  const file = await openInvoice(clients, config, req.params.orderId);
  if (!file) {
    res.status(404).json({ code: 'NOT_FOUND' });
    return;
  }
  res.type(file.contentType ?? 'application/pdf');
  if (file.contentLength) res.setHeader('Content-Length', file.contentLength);
  await pipeline(file.body, res); // streams, never buffers the whole file in memory
});

const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
  const status = err instanceof UploadError || err instanceof z.ZodError ? 400 : 500;
  res.status(status).json({ code: status === 400 ? 'BAD_REQUEST' : 'INTERNAL_ERROR', message: err.message });
};
app.use(errorHandler);

app.listen(config.PORT, () => console.info(`S3 demo on http://localhost:${config.PORT}`));

The file must be the last field of the form – S3 ignores fields after the file and returns a policy error. Errors come back as XML (e.g. EntityTooLarge, AccessDenied, Policy expired), so it is worth showing them in the browser logs.

Invoices: saving, presigned GET, streaming (Node.js, C#, Python)

src/invoices.ts
import { GetObjectCommand, NoSuchKey, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import type { Readable } from 'node:stream';
import type { Config } from './config.js';
import type { S3Clients } from './s3.js';

const invoiceKey = (orderId: string) => `invoices/${orderId}.pdf`;

export async function saveInvoice({ s3 }: S3Clients, config: Config, orderId: string, pdf: Uint8Array) {
  await s3.send(
    new PutObjectCommand({
      Bucket: config.PRIVATE_BUCKET,
      Key: invoiceKey(orderId),
      Body: pdf,
      ContentType: 'application/pdf',
      Metadata: { 'order-id': orderId }, // stored as x-amz-meta-order-id
    }),
  );
}

// Short-lived link for a customer who has already been authorized by the API.
export function invoiceDownloadUrl({ presigner }: S3Clients, config: Config, orderId: string): Promise<string> {
  const command = new GetObjectCommand({
    Bucket: config.PRIVATE_BUCKET,
    Key: invoiceKey(orderId),
    ResponseContentDisposition: `attachment; filename="pierogi-${orderId}.pdf"`,
  });
  return getSignedUrl(presigner, command, { expiresIn: 60 });
}

// Alternative: stream through the API (audit logs, watermarks, no S3 URL exposed).
export async function openInvoice({ s3 }: S3Clients, config: Config, orderId: string) {
  try {
    const res = await s3.send(new GetObjectCommand({ Bucket: config.PRIVATE_BUCKET, Key: invoiceKey(orderId) }));
    return { body: res.Body as Readable, contentType: res.ContentType, contentLength: res.ContentLength };
  } catch (err) {
    if (err instanceof NoSuchKey) return undefined;
    throw err;
  }
}
dotnet/S3Demo/Invoices.cs
using Amazon.S3;
using Amazon.S3.Model;

namespace S3Demo;

public sealed class Invoices(IAmazonS3 s3, string bucket)
{
    private static string KeyFor(string orderId) => $"invoices/{orderId}.pdf";

    public Task SaveAsync(string orderId, Stream pdf) =>
        s3.PutObjectAsync(new PutObjectRequest
        {
            BucketName = bucket,
            Key = KeyFor(orderId),
            InputStream = pdf,
            ContentType = "application/pdf",
        });

    // A one-minute link for a customer the API has already authorized.
    public Task<string> DownloadUrlAsync(string orderId) =>
        s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest
        {
            BucketName = bucket,
            Key = KeyFor(orderId),
            Verb = HttpVerb.GET,
            Expires = DateTime.UtcNow.AddMinutes(1),
            ResponseHeaderOverrides = { ContentDisposition = $"attachment; filename=\"pierogi-{orderId}.pdf\"" },
        });

    // Streaming through the API: copy S3's response stream without buffering the file.
    public async Task CopyToAsync(string orderId, Stream destination, CancellationToken ct = default)
    {
        using var response = await s3.GetObjectAsync(bucket, KeyFor(orderId), ct);
        await response.ResponseStream.CopyToAsync(destination, ct);
    }
}
python/invoices.py
from typing import BinaryIO

from s3_client import PRIVATE_BUCKET, s3


def _key(order_id: str) -> str:
    return f"invoices/{order_id}.pdf"


def save_invoice(order_id: str, pdf: bytes) -> None:
    s3.put_object(Bucket=PRIVATE_BUCKET, Key=_key(order_id), Body=pdf, ContentType="application/pdf")


def invoice_download_url(order_id: str) -> str:
    """A one-minute link for a customer the API has already authorized."""
    return s3.generate_presigned_url(
        "get_object",
        Params={
            "Bucket": PRIVATE_BUCKET,
            "Key": _key(order_id),
            "ResponseContentDisposition": f'attachment; filename="pierogi-{order_id}.pdf"',
        },
        ExpiresIn=60,
    )


def copy_invoice_to(order_id: str, destination: BinaryIO) -> None:
    """Stream through the API without loading the whole file into memory."""
    body = s3.get_object(Bucket=PRIVATE_BUCKET, Key=_key(order_id))["Body"]
    for chunk in body.iter_chunks(chunk_size=64 * 1024):
        destination.write(chunk)
  • Presigned GET with a 302 redirect – the API checks that the order belongs to the customer and returns a link valid for 60 seconds. The file comes from S3, not through your server. ResponseContentDisposition forces a download with a nice file name.
  • Streaming through the API (pipeline(body, res)) – when you want to log every download, add a watermark or hide S3 addresses. It costs server transfer, but memory stays constant.
  • NoSuchKey is an error class in the SDK – catch it and turn it into a 404 instead of letting a 500 through.

Step 7. Large files: multipart upload

A single PutObject accepts at most 5 GB, and a dropped connection means starting over. Multipart splits the file into parts sent in parallel, retrying individual parts.

Nightly export and paginated listing (Node.js, C#, Python)

src/exports.ts
import { createReadStream } from 'node:fs';
import { paginateListObjectsV2, type _Object } from '@aws-sdk/client-s3';
import { Upload } from '@aws-sdk/lib-storage';
import type { Config } from './config.js';
import type { S3Clients } from './s3.js';

// Multipart upload of a large file: parts in parallel, retries per part, constant memory.
export async function uploadDailyExport({ s3 }: S3Clients, config: Config, filePath: string, signal?: AbortSignal) {
  const key = `exports/${new Date().toISOString().slice(0, 10)}.csv.gz`;
  const upload = new Upload({
    client: s3,
    params: { Bucket: config.PRIVATE_BUCKET, Key: key, Body: createReadStream(filePath), ContentType: 'application/gzip' },
    partSize: 16 * 1024 * 1024, // min 5 MiB, max 10,000 parts per object
    queueSize: 4, // parts uploaded concurrently
    leavePartsOnError: false, // abort the multipart upload on failure
  });
  upload.on('httpUploadProgress', ({ loaded, total }) => {
    console.info(`export ${key}: ${loaded ?? 0}/${total ?? '?'} bytes`);
  });
  signal?.addEventListener('abort', () => void upload.abort());
  await upload.done();
  return key;
}

// Paginated listing – a single ListObjectsV2 call returns at most 1,000 keys.
export async function listExports({ s3 }: S3Clients, config: Config): Promise<_Object[]> {
  const objects: _Object[] = [];
  for await (const page of paginateListObjectsV2({ client: s3 }, { Bucket: config.PRIVATE_BUCKET, Prefix: 'exports/' })) {
    objects.push(...(page.Contents ?? []));
  }
  return objects;
}
dotnet/S3Demo/Exports.cs
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;

namespace S3Demo;

public sealed class Exports(IAmazonS3 s3, string bucket)
{
    // TransferUtility switches to multipart automatically for large files.
    public async Task<string> UploadDailyAsync(string filePath, CancellationToken ct = default)
    {
        var key = $"exports/{DateTime.UtcNow:yyyy-MM-dd}.csv.gz";
        var request = new TransferUtilityUploadRequest
        {
            BucketName = bucket,
            Key = key,
            FilePath = filePath,
            ContentType = "application/gzip",
            PartSize = 16 * 1024 * 1024,
        };
        request.UploadProgressEvent += (_, e) => Console.WriteLine($"{key}: {e.TransferredBytes}/{e.TotalBytes} bytes");

        using var transfer = new TransferUtility(s3);
        await transfer.UploadAsync(request, ct);
        return key;
    }

    // Paginator: ListObjectsV2 returns at most 1,000 keys per call.
    public async Task<List<string>> ListAsync(CancellationToken ct = default)
    {
        var keys = new List<string>();
        var pages = s3.Paginators.ListObjectsV2(new ListObjectsV2Request { BucketName = bucket, Prefix = "exports/" });
        await foreach (var page in pages.Responses.WithCancellation(ct))
            keys.AddRange((page.S3Objects ?? []).Select(o => o.Key));
        return keys;
    }
}
python/exports.py
from datetime import date

from boto3.s3.transfer import TransferConfig

from s3_client import PRIVATE_BUCKET, s3

# upload_file switches to multipart above the threshold and uploads parts in parallel.
TRANSFER = TransferConfig(multipart_threshold=16 * 1024 * 1024, multipart_chunksize=16 * 1024 * 1024, max_concurrency=4)


def upload_daily_export(file_path: str) -> str:
    key = f"exports/{date.today().isoformat()}.csv.gz"
    s3.upload_file(
        file_path,
        PRIVATE_BUCKET,
        key,
        ExtraArgs={"ContentType": "application/gzip"},
        Config=TRANSFER,
        Callback=lambda sent: print(f"{key}: +{sent} bytes"),
    )
    return key


def list_exports() -> list[str]:
    """The paginator follows continuation tokens – one call returns at most 1,000 keys."""
    keys: list[str] = []
    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=PRIVATE_BUCKET, Prefix="exports/"):
        keys.extend(obj["Key"] for obj in page.get("Contents", []))
    return keys

Upload from @aws-sdk/lib-storage (TransferUtility in C#, upload_file in Python) does everything for you: CreateMultipartUpload, parallel UploadPart, CompleteMultipartUpload, and AbortMultipartUpload on failure. A file stream means constant memory use – roughly partSize × queueSize.

Step 8. CloudFront in front of S3

Every visitor views the menu photos. Serving them straight from S3 means a public bucket, no cache closer to the customer and more expensive transfer. CloudFront solves all three.

Bucket policy for CloudFront (OAC) and signed URLs

infra/bucket-policy-cloudfront.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontOriginAccessControl",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::pierogi-media-123456789012/menu/*",
      "Condition": {
        "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E2EXAMPLE123" }
      }
    }
  ]
}
src/cdn.ts
import { getSignedUrl } from '@aws-sdk/cloudfront-signer';

// Private content through CloudFront (e.g. recipe videos for paying members):
// a signed URL checked at the edge, the bucket stays closed behind Origin Access Control.
export function signedCdnUrl(path: string, opts: { cdnUrl: string; keyPairId: string; privateKey: string }) {
  return getSignedUrl({
    url: `${opts.cdnUrl}/${path}`,
    keyPairId: opts.keyPairId, // public key id from a CloudFront key group
    privateKey: opts.privateKey, // PEM from Secrets Manager, never from the repository
    dateLessThan: new Date(Date.now() + 10 * 60_000).toISOString(),
  });
}
  1. Create a CloudFront distribution with the media bucket as the origin and Origin Access Control (OAC) – CloudFront signs its requests to S3.
  2. Add a bucket policy with Principal: cloudfront.amazonaws.com and an AWS:SourceArn condition pointing at your distribution – no other distribution and nobody on the internet can read the objects.
  3. Object keys are immutable (menu/ruskie/<uuid>.webp) and carry Cache-Control: max-age=31536000, immutable – a new photo = a new key, so you do not need costly cache invalidations.
  4. For paid content (e.g. pierogi-making videos for club members) use CloudFront signed URLs (@aws-sdk/cloudfront-signer) with a key from a key group.

OAC replaced the older Origin Access Identity (OAI) mechanism – use OAC for new distributions.

Step 9. Lifecycle and storage classes

Lifecycle rules for the private bucket

infra/lifecycle.json
{
  "Rules": [
    {
      "ID": "abort-incomplete-multipart-uploads",
      "Status": "Enabled",
      "Filter": {},
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    },
    {
      "ID": "exports-to-glacier-then-delete",
      "Status": "Enabled",
      "Filter": { "Prefix": "exports/" },
      "Transitions": [{ "Days": 30, "StorageClass": "GLACIER_IR" }],
      "Expiration": { "Days": 365 }
    },
    {
      "ID": "old-invoices-to-infrequent-access",
      "Status": "Enabled",
      "Filter": { "Prefix": "invoices/" },
      "Transitions": [{ "Days": 90, "StorageClass": "STANDARD_IA" }]
    }
  ]
}
ClassFor whatNotes
S3 Standardfrequently read data (menu photos)no retrieval fees
S3 Intelligent-Tieringunpredictable accessmoves objects between tiers by itself, small per-object monitoring fee
S3 Standard-IArarely read but needed instantly (old invoices)min. 30 days and 128 KB per object, per-GB retrieval fee
S3 Glacier Instant Retrievalan archive read once a quartermillisecond reads, min. 90 days
Glacier Flexible / Deep Archive"just in case" archivesrestores take minutes to hours (Deep Archive: up to 12 h or more)

Invoices must be kept for years, so they have no Expiration rule – only a transition to Standard-IA after 90 days. Exports move to Glacier Instant Retrieval after 30 days and are deleted after a year.

Costs: what you pay for

Approximate prices for us-east-1 (eu-central-1 is a few percent higher) – check the current price list and the AWS calculator before deciding.

ItemApproximate priceWatch out for
S3 Standard storageabout USD 0.023 per GB-monthversioning keeps every version
PUT, POST, LISTabout USD 0.005 per 1,000 requestsmillions of small files = many requests
GETabout USD 0.0004 per 1,000 requests
S3 → internet transferabout USD 0.09 per GB (after the free 100 GB/month per account)usually the largest item for public files
S3 → CloudFront transferUSD 0CloudFront has its own price list and a free 1 TB/month tier

The most common surprises: internet transfer from a public bucket without a CDN, unfinished multipart uploads, old object versions without a NoncurrentVersionExpiration rule, and LIST requests in a loop every second.

C# and Python variants

The C# and Python snippets in steps 4, 6 and 7 form complete mini-projects. Client configuration and entry points:

C# (AWSSDK.S3 4.x) and Python (boto3) projects

dotnet/S3Demo/S3Demo.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AWSSDK.S3" Version="4.1.2.1" />
  </ItemGroup>

</Project>
dotnet/S3Demo/Program.cs
using Amazon;
using Amazon.S3;
using S3Demo;

// Credentials and region come from the default chain (AWS_PROFILE, env vars, IAM role).
var region = RegionEndpoint.GetBySystemName(Environment.GetEnvironmentVariable("AWS_REGION") ?? "eu-central-1");
using var s3 = new AmazonS3Client(new AmazonS3Config { RegionEndpoint = region });

var mediaBucket = Environment.GetEnvironmentVariable("MEDIA_BUCKET") ?? "pierogi-media-123456789012";
var privateBucket = Environment.GetEnvironmentVariable("PRIVATE_BUCKET") ?? "pierogi-private-123456789012";

var upload = await new PhotoUploads(s3, mediaBucket, 5 * 1024 * 1024).CreateAsync("ruskie", "image/webp");
Console.WriteLine($"POST {upload.Url} with {upload.Fields.Count} form fields, key {upload.Key}");

var link = await new Invoices(s3, privateBucket).DownloadUrlAsync("o-42");
Console.WriteLine($"Invoice link: {link}");
python/requirements.txt
boto3>=1.44
python/s3_client.py
import os

import boto3
from botocore.config import Config

# Credentials come from the default chain (AWS_PROFILE, env vars, IAM role) – never from code.
REGION = os.environ.get("AWS_REGION", "eu-central-1")
MEDIA_BUCKET = os.environ.get("MEDIA_BUCKET", "pierogi-media-123456789012")
PRIVATE_BUCKET = os.environ.get("PRIVATE_BUCKET", "pierogi-private-123456789012")

s3 = boto3.client(
    "s3",
    region_name=REGION,
    config=Config(
        signature_version="s3v4",
        # Regional virtual-hosted URLs (bucket.s3.<region>.amazonaws.com) – the legacy global
        # endpoint answers with a redirect for buckets outside us-east-1, which breaks browser uploads.
        s3={"addressing_style": "virtual"},
        # Presigned URLs for browsers: no checksum of an empty body inside the URL.
        request_checksum_calculation="when_required",
    ),
)
python/main.py
from invoices import invoice_download_url
from photo_uploads import create_photo_upload

if __name__ == "__main__":
    upload = create_photo_upload("ruskie", "image/webp")
    print("POST", upload["url"], "fields:", sorted(upload["fields"]), "key:", upload["key"])
    print("Invoice link:", invoice_download_url("o-42")[:120], "...")
  • C#: AWSSDK 4.x has async GetPreSignedURLAsync and CreatePresignedPostAsync with S3PostCondition conditions, and response collections may be null (hence page.S3Objects ?? []). In ASP.NET Core register the client via AWSSDK.Extensions.NETCore.Setup (services.AddAWSService<IAmazonS3>()).
  • Python: set addressing_style: virtual so boto3 generates regional addresses (bucket.s3.eu-central-1.amazonaws.com). Without it I got an address on the global endpoint, which for buckets outside us-east-1 may answer with a redirect – and a redirect breaks browser uploads (CORS).

Locally without AWS: LocalStack or MinIO emulate the S3 API. In Node set S3_ENDPOINT=http://localhost:4566 (the client gets forcePathStyle: true), in Python endpoint_url, in C# ServiceURL and ForcePathStyle = true.

Common mistakes

  • Object keys from user file names – ../../, non-ASCII characters, collisions and personal data in URLs. Generate your own keys.
  • Presigned PUT without a size limit – someone uploads 5 GB into your bucket and you pay for storing it. Use presigned POST for user uploads.
  • Creating a new S3Client per request – no connection pool and a credential lookup every time.
  • Reading res.Body into memory (transformToByteArray()) for large files – use streams.
  • No CORS or AllowedOrigins: ["*"] – the first blocks browser uploads, the second lets any website use your signed forms in victims' browsers.

S3 as file storage

  • practically unlimited capacity and 11 nines of durability
  • pay per use, no file servers to maintain
  • integrations: CloudFront, Lambda (events), Athena, cross-region replication
  • strong read-after-write consistency

S3 limitations

  • not a file system: no appending to a file, rename = copy + delete
  • internet transfer can dominate the bill
  • latency of tens of ms per request – not for millions of tiny reads in a loop

Check yourself

Question: The cook uploads photos from the browser, 5 MB max. Which approach enforces the limit on the S3 side?

  • Presigned PUT with `expiresIn: 60`
  • Presigned POST with a `content-length-range` condition
  • Checking `file.size` in JavaScript before sending

Question: A browser upload via a presigned PUT from SDK v3 fails with a checksum error even though the signature is valid. The most likely cause?

  • The SDK put an `x-amz-checksum-crc32` computed from an empty body into the URL
  • No SSE-S3 encryption on the bucket
  • Too short `expiresIn`
Interview question: how would you design large file uploads from users to S3?

A good answer: the browser sends the file directly to S3 and the backend only authorizes and signs (a presigned POST with size and type limits or – for very large files – multipart with presigned URLs per part: CreateMultipartUpload on the server, presigned UploadPart for the client, CompleteMultipartUpload on the server). The server generates the key. After the upload: HeadObject verification, asynchronous scanning and processing (S3 event → SQS/Lambda), metadata saved in the database only after validation. A private bucket, CORS for specific origins, an AbortIncompleteMultipartUpload rule, serving through CloudFront. Bonus points for mentioning transfer costs and that a presigned URL carries the signer's permissions.

What's next