{"id":"6b09417b5ce40d447918f285","slug":"aws-s3","title":"AWS S3 in practice – browser uploads, presigned URLs, multipart, CloudFront and costs (Node.js, C#, Python)","summary":"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).","servedLang":"en","availableLangs":["pl","en"],"topics":["aws-s3"],"techs":["node","typescript","dotnet","python"],"tags":["aws","s3","aws-sdk-v3","presigned-url","multipart-upload","cloudfront","iam","lifecycle","boto3","awssdk"],"level":"intermediate","kind":"tutorial","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":26,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:19.920Z","updatedAt":"2026-11-27T13:10:06.088Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Amazon S3 step by step – @aws-sdk/client-s3, presigned POST and PUT, getSignedUrl, @aws-sdk/lib-storage (multipart), CloudFront OAC and signed URLs, IAM least privilege, CORS, lifecycle, storage classes, costs; examples in Node.js, C# and Python.","wordCount":5012,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"callout","attrs":{"variant":"info","title":"In a nutshell"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"User files go from the browser straight to S3","marks":[{"type":"bold"}]},{"type":"text","text":" through a signed form (presigned POST) with size and type limits – the API only signs and verifies the result."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The bucket is private.","marks":[{"type":"bold"}]},{"type":"text","text":" Public photos are served by CloudFront with Origin Access Control, private files by short-lived presigned URLs or streaming through the API."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The app has no access keys in code","marks":[{"type":"bold"}]},{"type":"text","text":" – an IAM role with permissions on specific prefixes, and lifecycle rules clean up unfinished uploads and move old data to cheaper classes."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A file module for the pierogi shop API in Node.js (AWS SDK v3): signing a dish photo upload and verifying it, a browser function that sends the file to S3, an invoice link valid for 60 seconds, invoice streaming through the API, a multipart export upload with progress, CloudFront signed URLs, and IAM, CORS, bucket and lifecycle policies. The same operations in C# (AWSSDK.S3 4.x) and Python (boto3). Download the code (27 files) as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" an AWS account with console access and AWS CLI v2 (signing in via "},{"type":"text","text":"aws configure sso","marks":[{"type":"code"}]},{"type":"text","text":" or a profile), Node.js 22+, Express basics ("},{"type":"text","text":"Express tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/express"}}]},{"type":"text","text":"). For the variants: .NET 10 SDK or Python 3.10+."}]},{"type":"stats","attrs":{"items":[{"value":"11 nines","label":"of designed durability","hint":"99.999999999% over a year"},{"value":"5 GB","label":"max single PUT","hint":"larger files only via multipart"},{"value":"10,000","label":"parts per multipart upload","hint":"each from 5 MiB to 5 GiB"},{"value":"1,000","label":"keys per list page","hint":"pagination beyond that"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  U([Cook / customer]) -->|1. ask for a signature| API[Pierogi API<br/>IAM role]\n  API -->|presigned POST / GET| U\n  U -->|2. upload straight to S3| M[(media bucket<br/>private)]\n  U -->|menu photos| CF[CloudFront<br/>edge cache]\n  CF -->|Origin Access Control| M\n  API -->|PutObject, HeadObject| M\n  API -->|invoices, exports| P[(private bucket)]\n  U -->|60 s link| P","caption":"Architecture: who talks to whom and with which permissions"}},{"type":"heading","attrs":{"level":2,"id":"step-1-buckets-with-safe-settings"},"content":[{"type":"text","text":"Step 1. Buckets with safe settings"}]},{"type":"paragraph","content":[{"type":"text","text":"We create two buckets: "},{"type":"text","text":"media","marks":[{"type":"code"}]},{"type":"text","text":" for menu photos (public, but only through CloudFront) and "},{"type":"text","text":"private","marks":[{"type":"code"}]},{"type":"text","text":" for invoices and exports. Names are globally unique, so we append the account number."}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"REGION=eu-central-1\nACCOUNT=$(aws sts get-caller-identity --query Account --output text)\nfor B in pierogi-media-$ACCOUNT pierogi-private-$ACCOUNT; do\n  aws s3api create-bucket --bucket $B --region $REGION \\\n    --create-bucket-configuration LocationConstraint=$REGION\ndone\naws s3api put-bucket-cors --bucket pierogi-media-$ACCOUNT --cors-configuration file://infra/bucket-cors.json\naws s3api put-bucket-lifecycle-configuration --bucket pierogi-private-$ACCOUNT --lifecycle-configuration file://infra/lifecycle.json\naws s3api put-bucket-versioning --bucket pierogi-private-$ACCOUNT --versioning-configuration Status=Enabled"}]},{"type":"paragraph","content":[{"type":"text","text":"The good news: since 2023 new buckets have "},{"type":"text","text":"Block Public Access","marks":[{"type":"bold"}]},{"type":"text","text":" on, ACLs disabled (Object Ownership = "},{"type":"text","text":"Bucket owner enforced","marks":[{"type":"italic"}]},{"type":"text","text":") 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."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-the-project-and-s3-clients"},"content":[{"type":"text","text":"Step 2. The project and S3 clients"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"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"}]},{"type":"codeGroup","attrs":{"title":"Configuration and S3 clients (Node.js)"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-s3\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=22.12\" },\n  \"scripts\": {\n    \"dev\": \"tsx watch --env-file-if-exists=.env src/server.ts\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"start\": \"node --env-file-if-exists=.env dist/server.js\",\n    \"typecheck\": \"tsc --noEmit\"\n  },\n  \"dependencies\": {\n    \"@aws-sdk/client-s3\": \"^3.1178.0\",\n    \"@aws-sdk/cloudfront-signer\": \"^3.1177.0\",\n    \"@aws-sdk/lib-storage\": \"^3.1178.0\",\n    \"@aws-sdk/s3-presigned-post\": \"^3.1178.0\",\n    \"@aws-sdk/s3-request-presigner\": \"^3.1178.0\",\n    \"express\": \"^5.3.0\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"tsx\": \"^4.23.15\",\n    \"typescript\": \"^7.0.2\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"ES2024\",\n    \"module\": \"nodenext\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"noEmit\": true,\n    \"types\": [\"node\"]\n  },\n  \"include\": [\"src\", \"web\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.build.json"},"content":[{"type":"text","text":"{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": { \"noEmit\": false, \"rootDir\": \"src\", \"outDir\": \"dist\" },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":".env.example"},"content":[{"type":"text","text":"PORT=3000\nAWS_REGION=eu-central-1\nMEDIA_BUCKET=pierogi-media-123456789012\nPRIVATE_BUCKET=pierogi-private-123456789012\nCDN_URL=https://d111111abcdef8.cloudfront.net\nMAX_PHOTO_BYTES=5242880\n# Local development with LocalStack: S3_ENDPOINT=http://localhost:4566\n# Credentials come from `aws configure sso` / AWS_PROFILE – never put keys here."}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/config.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nconst EnvSchema = z.object({\n  PORT: z.coerce.number().int().default(3000),\n  AWS_REGION: z.string().default('eu-central-1'),\n  // Public menu photos (served through CloudFront) and private documents.\n  MEDIA_BUCKET: z.string().min(3),\n  PRIVATE_BUCKET: z.string().min(3),\n  CDN_URL: z.url(), // e.g. https://d111111abcdef8.cloudfront.net\n  MAX_PHOTO_BYTES: z.coerce.number().int().positive().default(5 * 1024 * 1024),\n  // Only for LocalStack/MinIO in development – leave empty in AWS.\n  S3_ENDPOINT: z.url().optional(),\n});\n\nexport type Config = z.infer<typeof EnvSchema>;\nexport const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => EnvSchema.parse(env);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/s3.ts"},"content":[{"type":"text","text":"import { S3Client } from '@aws-sdk/client-s3';\nimport type { Config } from './config.js';\n\n// No credentials in code: the default provider chain finds them\n// (AWS_PROFILE / env vars locally, the IAM role on ECS, Lambda or EC2).\nexport function createS3Clients(config: Config) {\n  const common = {\n    region: config.AWS_REGION,\n    ...(config.S3_ENDPOINT ? { endpoint: config.S3_ENDPOINT, forcePathStyle: true } : {}),\n  };\n  return {\n    // Regular client: SDK-side integrity checksums stay on (default since v3.729).\n    s3: new S3Client(common),\n    // Client for presigned URLs used by browsers: no checksum of an empty body baked into the URL.\n    presigner: new S3Client({ ...common, requestChecksumCalculation: 'WHEN_REQUIRED' }),\n  };\n}\n\nexport type S3Clients = ReturnType<typeof createS3Clients>;"}]}]},{"type":"paragraph","content":[{"type":"text","text":"AWS SDK v3 is modular: you install only the service client ("},{"type":"text","text":"@aws-sdk/client-s3","marks":[{"type":"code"}]},{"type":"text","text":") and the tools you need, and every operation is a command object sent with "},{"type":"text","text":"client.send()","marks":[{"type":"code"}]},{"type":"text","text":". A client is expensive to create (connection pool, credential lookup) – create it once and share it."}]},{"type":"paragraph","content":[{"type":"text","text":"Why two clients?","marks":[{"type":"bold"}]},{"type":"text","text":" 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 "},{"type":"text","text":"x-amz-checksum-crc32","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"requestChecksumCalculation: 'WHEN_REQUIRED'","marks":[{"type":"code"}]},{"type":"text","text":" used only for signing solves the problem without disabling integrity protection for other operations."}]},{"type":"callout","attrs":{"variant":"info","title":"Credentials: zero keys in code and in .env"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Locally sign in with "},{"type":"text","text":"aws configure sso","marks":[{"type":"code"}]},{"type":"text","text":" (temporary credentials); on ECS, Lambda or EC2 the app gets an IAM role. The SDK finds credentials in the default chain by itself. Long-term "},{"type":"text","text":"AKIA…","marks":[{"type":"code"}]},{"type":"text","text":" keys in a repository are an invitation for bots scanning GitHub – they can find them within minutes."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-3-iam-the-least-privilege-possible"},"content":[{"type":"text","text":"Step 3. IAM: the least privilege possible"}]},{"type":"paragraph","content":[{"type":"text","text":"The app's role gets exactly what it needs, and only within its prefixes."}]},{"type":"codeGroup","attrs":{"title":"App role IAM policy and bucket CORS"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"infra/iam-policy.json"},"content":[{"type":"text","text":"{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"MenuPhotos\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\"s3:PutObject\", \"s3:GetObject\", \"s3:DeleteObject\"],\n      \"Resource\": \"arn:aws:s3:::pierogi-media-123456789012/menu/*\"\n    },\n    {\n      \"Sid\": \"Invoices\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\"s3:PutObject\", \"s3:GetObject\"],\n      \"Resource\": \"arn:aws:s3:::pierogi-private-123456789012/invoices/*\"\n    },\n    {\n      \"Sid\": \"Exports\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\"s3:PutObject\", \"s3:AbortMultipartUpload\"],\n      \"Resource\": \"arn:aws:s3:::pierogi-private-123456789012/exports/*\"\n    },\n    {\n      \"Sid\": \"ListExportsOnly\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"s3:ListBucket\",\n      \"Resource\": \"arn:aws:s3:::pierogi-private-123456789012\",\n      \"Condition\": { \"StringLike\": { \"s3:prefix\": [\"exports/*\"] } }\n    }\n  ]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"infra/bucket-cors.json"},"content":[{"type":"text","text":"{\n  \"CORSRules\": [\n    {\n      \"AllowedOrigins\": [\"https://admin.pierogarnia.example\", \"http://localhost:5173\"],\n      \"AllowedMethods\": [\"POST\", \"PUT\"],\n      \"AllowedHeaders\": [\"*\"],\n      \"ExposeHeaders\": [\"ETag\"],\n      \"MaxAgeSeconds\": 3000\n    }\n  ]\n}"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A presigned URL carries the permissions of whoever signed it.","marks":[{"type":"bold"}]},{"type":"text","text":" The API role needs "},{"type":"text","text":"s3:PutObject","marks":[{"type":"code"}]},{"type":"text","text":" on "},{"type":"text","text":"menu/*","marks":[{"type":"code"}]},{"type":"text","text":", otherwise signed forms are rejected. There is no separate \"signing\" permission."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"HeadObject","marks":[{"type":"code"}]},{"type":"text","text":" requires "},{"type":"text","text":"s3:GetObject","marks":[{"type":"code"}]},{"type":"text","text":", listing requires "},{"type":"text","text":"s3:ListBucket","marks":[{"type":"code"}]},{"type":"text","text":" on the bucket (not on objects), narrowed with an "},{"type":"text","text":"s3:prefix","marks":[{"type":"code"}]},{"type":"text","text":" condition."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"s3:AbortMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" lets the SDK clean up after a failed multipart upload."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"CORS","marks":[{"type":"bold"}]},{"type":"text","text":" is needed because the browser sends the form from the panel's domain to the S3 domain. Only specific origins and methods – no "},{"type":"text","text":"*","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-4-browser-uploads-presigned-post"},"content":[{"type":"text","text":"Step 4. Browser uploads: presigned POST"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant B as Panel (browser)\n  participant A as API\n  participant S as S3 (media bucket)\n  B->>A: POST /api/dishes/ruskie/photo-uploads (image/webp)\n  A->>A: authorization, own key menu/ruskie/uuid.webp\n  A-->>B: url + form fields (policy, signature), valid 5 min\n  B->>S: POST multipart/form-data (fields + file)\n  S->>S: checks signature, size 1 B–5 MiB, Content-Type\n  S-->>B: 204 No Content\n  B->>A: PUT /api/dishes/ruskie/photo { key }\n  A->>S: HeadObject – what really arrived?\n  A-->>B: photo URL on CloudFront","caption":"Uploading a dish photo via presigned POST"}},{"type":"codeGroup","attrs":{"title":"Signed upload and verification (Node.js, C#, Python)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/photos.ts"},"content":[{"type":"text","text":"import { randomUUID } from 'node:crypto';\nimport { DeleteObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';\nimport { createPresignedPost } from '@aws-sdk/s3-presigned-post';\nimport type { Config } from './config.js';\nimport type { S3Clients } from './s3.js';\n\nconst EXTENSIONS: Record<string, string> = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp' };\n\nexport class UploadError extends Error {}\n\n// Step 1: the API signs an upload; the browser sends the file straight to S3.\nexport async function createPhotoUpload({ presigner }: S3Clients, config: Config, dishId: string, contentType: string) {\n  const ext = EXTENSIONS[contentType];\n  if (!ext) throw new UploadError(`Unsupported type ${contentType}`);\n  // Our own key – never the user's file name (path tricks, collisions, PII in URLs).\n  const key = `menu/${dishId}/${randomUUID()}.${ext}`;\n  const { url, fields } = await createPresignedPost(presigner, {\n    Bucket: config.MEDIA_BUCKET,\n    Key: key,\n    // S3 itself rejects files that are too big – something a presigned PUT cannot enforce.\n    Conditions: [['content-length-range', 1, config.MAX_PHOTO_BYTES]],\n    // Every field below becomes an exact-match condition of the signed policy.\n    Fields: { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=31536000, immutable' },\n    Expires: 300, // seconds\n  });\n  return { url, fields, key };\n}\n\n// Step 2: the browser reports the key; we check what really landed in S3.\nexport async function confirmPhoto({ s3 }: S3Clients, config: Config, dishId: string, key: string) {\n  if (!key.startsWith(`menu/${dishId}/`)) throw new UploadError('Key does not belong to this dish');\n  const head = await s3.send(new HeadObjectCommand({ Bucket: config.MEDIA_BUCKET, Key: key }));\n  if (!head.ContentType || !(head.ContentType in EXTENSIONS) || (head.ContentLength ?? 0) > config.MAX_PHOTO_BYTES) {\n    await s3.send(new DeleteObjectCommand({ Bucket: config.MEDIA_BUCKET, Key: key }));\n    throw new UploadError('Uploaded file rejected');\n  }\n  return { key, size: head.ContentLength, url: `${config.CDN_URL}/${key}` };\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"dotnet/S3Demo/PhotoUploads.cs"},"content":[{"type":"text","text":"using Amazon.S3;\nusing Amazon.S3.Model;\n\nnamespace S3Demo;\n\npublic sealed record PhotoUpload(string Url, IDictionary<string, string> Fields, string Key);\n\npublic sealed class PhotoUploads(IAmazonS3 s3, string bucket, long maxBytes)\n{\n    private static readonly Dictionary<string, string> Extensions = new()\n    {\n        [\"image/jpeg\"] = \"jpg\",\n        [\"image/png\"] = \"png\",\n        [\"image/webp\"] = \"webp\",\n    };\n\n    // Presigned POST: S3 enforces the size range and the content type itself.\n    public async Task<PhotoUpload> CreateAsync(string dishId, string contentType)\n    {\n        if (!Extensions.TryGetValue(contentType, out var ext))\n            throw new ArgumentException($\"Unsupported type {contentType}\");\n\n        var key = $\"menu/{dishId}/{Guid.NewGuid()}.{ext}\";\n        var response = await s3.CreatePresignedPostAsync(new CreatePresignedPostRequest\n        {\n            BucketName = bucket,\n            Key = key,\n            Expires = DateTime.UtcNow.AddMinutes(5),\n            Conditions =\n            [\n                S3PostCondition.ContentLengthRange(1, maxBytes),\n                S3PostCondition.ExactMatch(\"Content-Type\", contentType),\n            ],\n            Fields = new Dictionary<string, string> { [\"Content-Type\"] = contentType },\n        });\n        return new PhotoUpload(response.Url, response.Fields, key);\n    }\n\n    // After the browser reports success: check what really landed in the bucket.\n    public async Task<long> ConfirmAsync(string dishId, string key)\n    {\n        if (!key.StartsWith($\"menu/{dishId}/\", StringComparison.Ordinal))\n            throw new ArgumentException(\"Key does not belong to this dish\");\n        var head = await s3.GetObjectMetadataAsync(bucket, key);\n        if (head.ContentLength > maxBytes || !Extensions.ContainsKey(head.Headers.ContentType ?? \"\"))\n        {\n            await s3.DeleteObjectAsync(bucket, key);\n            throw new InvalidOperationException(\"Uploaded file rejected\");\n        }\n        return head.ContentLength;\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/photo_uploads.py"},"content":[{"type":"text","text":"import uuid\n\nfrom s3_client import MEDIA_BUCKET, s3\n\nEXTENSIONS = {\"image/jpeg\": \"jpg\", \"image/png\": \"png\", \"image/webp\": \"webp\"}\nMAX_BYTES = 5 * 1024 * 1024\n\n\ndef create_photo_upload(dish_id: str, content_type: str) -> dict:\n    \"\"\"Presigned POST: S3 itself enforces the size range and the content type.\"\"\"\n    ext = EXTENSIONS.get(content_type)\n    if ext is None:\n        raise ValueError(f\"Unsupported type {content_type}\")\n    key = f\"menu/{dish_id}/{uuid.uuid4()}.{ext}\"\n    post = s3.generate_presigned_post(\n        Bucket=MEDIA_BUCKET,\n        Key=key,\n        Fields={\"Content-Type\": content_type},\n        Conditions=[\n            [\"content-length-range\", 1, MAX_BYTES],\n            {\"Content-Type\": content_type},\n        ],\n        ExpiresIn=300,\n    )\n    return {\"url\": post[\"url\"], \"fields\": post[\"fields\"], \"key\": key}\n\n\ndef confirm_photo(dish_id: str, key: str) -> int:\n    \"\"\"Check what really landed in S3 before saving the key in the database.\"\"\"\n    if not key.startswith(f\"menu/{dish_id}/\"):\n        raise ValueError(\"Key does not belong to this dish\")\n    head = s3.head_object(Bucket=MEDIA_BUCKET, Key=key)\n    if head[\"ContentLength\"] > MAX_BYTES or head.get(\"ContentType\") not in EXTENSIONS:\n        s3.delete_object(Bucket=MEDIA_BUCKET, Key=key)\n        raise ValueError(\"Uploaded file rejected\")\n    return head[\"ContentLength\"]"}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Presigned PUT"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Presigned POST"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Call"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"getSignedUrl(client, new PutObjectCommand(...))","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"createPresignedPost(client, { Conditions })","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Size limit"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"none – the client can send up to 5 GB"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"content-length-range","marks":[{"type":"code"}]},{"type":"text","text":" in the policy"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"File type"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Content-Type","marks":[{"type":"code"}]},{"type":"text","text":" unsigned unless you add it to "},{"type":"text","text":"signableHeaders","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"exact match or "},{"type":"text","text":"starts-with","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the browser"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"fetch(url, { method: 'PUT', body: file })","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"FormData","marks":[{"type":"code"}]},{"type":"text","text":" with fields and the file last"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"uploads from trusted servers, CLI tools"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"uploads from users"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Verification after the upload ("},{"type":"text","text":"confirmPhoto","marks":[{"type":"code"}]},{"type":"text","text":") 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 "},{"type":"text","text":"s3:ObjectCreated","marks":[{"type":"code"}]},{"type":"text","text":" event that stores a safe, resized copy."}]},{"type":"heading","attrs":{"level":2,"id":"step-5-the-browser-and-api-routes"},"content":[{"type":"text","text":"Step 5. The browser and API routes"}]},{"type":"codeGroup","attrs":{"title":"Browser function and Express server"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"web/upload-photo.ts"},"content":[{"type":"text","text":"// Browser side: ask the API for a signed form, then POST the file directly to S3.\nexport async function uploadDishPhoto(dishId: string, file: File, accessToken: string): Promise<string> {\n  const headers = { 'content-type': 'application/json', authorization: `Bearer ${accessToken}` };\n  const signed = await fetch(`/api/dishes/${dishId}/photo-uploads`, {\n    method: 'POST',\n    headers,\n    body: JSON.stringify({ contentType: file.type }),\n  });\n  if (!signed.ok) throw new Error(`Cannot start upload: ${signed.status}`);\n  const { url, fields, key } = (await signed.json()) as { url: string; fields: Record<string, string>; key: string };\n\n  const form = new FormData();\n  for (const [name, value] of Object.entries(fields)) form.append(name, value);\n  form.append('file', file); // the file must be the LAST field of the form\n\n  const uploaded = await fetch(url, { method: 'POST', body: form });\n  // 204 = stored; 403 with EntityTooLarge / policy errors comes back as XML.\n  if (!uploaded.ok) throw new Error(`S3 rejected the file: ${uploaded.status} ${await uploaded.text()}`);\n\n  const confirmed = await fetch(`/api/dishes/${dishId}/photo`, { method: 'PUT', headers, body: JSON.stringify({ key }) });\n  if (!confirmed.ok) throw new Error(`Upload not accepted: ${confirmed.status}`);\n  return ((await confirmed.json()) as { url: string }).url;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/server.ts"},"content":[{"type":"text","text":"import { pipeline } from 'node:stream/promises';\nimport express, { type ErrorRequestHandler } from 'express';\nimport { z } from 'zod';\nimport { loadConfig } from './config.js';\nimport { invoiceDownloadUrl, openInvoice } from './invoices.js';\nimport { confirmPhoto, createPhotoUpload, UploadError } from './photos.js';\nimport { createS3Clients } from './s3.js';\n\nconst config = loadConfig();\nconst clients = createS3Clients(config);\nconst app = express();\napp.use(express.json());\n\n// In a real app these routes sit behind authentication and authorization (staff / order owner).\napp.post('/api/dishes/:dishId/photo-uploads', async (req, res) => {\n  const { contentType } = z.object({ contentType: z.string() }).parse(req.body);\n  res.status(201).json(await createPhotoUpload(clients, config, req.params.dishId, contentType));\n});\n\napp.put('/api/dishes/:dishId/photo', async (req, res) => {\n  const { key } = z.object({ key: z.string() }).parse(req.body);\n  res.json(await confirmPhoto(clients, config, req.params.dishId, key));\n});\n\napp.get('/api/orders/:orderId/invoice', async (req, res) => {\n  res.redirect(302, await invoiceDownloadUrl(clients, config, req.params.orderId));\n});\n\napp.get('/api/orders/:orderId/invoice/stream', async (req, res) => {\n  const file = await openInvoice(clients, config, req.params.orderId);\n  if (!file) {\n    res.status(404).json({ code: 'NOT_FOUND' });\n    return;\n  }\n  res.type(file.contentType ?? 'application/pdf');\n  if (file.contentLength) res.setHeader('Content-Length', file.contentLength);\n  await pipeline(file.body, res); // streams, never buffers the whole file in memory\n});\n\nconst errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {\n  const status = err instanceof UploadError || err instanceof z.ZodError ? 400 : 500;\n  res.status(status).json({ code: status === 400 ? 'BAD_REQUEST' : 'INTERNAL_ERROR', message: err.message });\n};\napp.use(errorHandler);\n\napp.listen(config.PORT, () => console.info(`S3 demo on http://localhost:${config.PORT}`));"}]}]},{"type":"paragraph","content":[{"type":"text","text":"The file must be the "},{"type":"text","text":"last field","marks":[{"type":"bold"}]},{"type":"text","text":" of the form – S3 ignores fields after the file and returns a policy error. Errors come back as XML (e.g. "},{"type":"text","text":"EntityTooLarge","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"AccessDenied","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Policy expired","marks":[{"type":"code"}]},{"type":"text","text":"), so it is worth showing them in the browser logs."}]},{"type":"heading","attrs":{"level":2,"id":"step-6-downloads-a-short-link-or-streaming"},"content":[{"type":"text","text":"Step 6. Downloads: a short link or streaming"}]},{"type":"codeGroup","attrs":{"title":"Invoices: saving, presigned GET, streaming (Node.js, C#, Python)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/invoices.ts"},"content":[{"type":"text","text":"import { GetObjectCommand, NoSuchKey, PutObjectCommand } from '@aws-sdk/client-s3';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport type { Readable } from 'node:stream';\nimport type { Config } from './config.js';\nimport type { S3Clients } from './s3.js';\n\nconst invoiceKey = (orderId: string) => `invoices/${orderId}.pdf`;\n\nexport async function saveInvoice({ s3 }: S3Clients, config: Config, orderId: string, pdf: Uint8Array) {\n  await s3.send(\n    new PutObjectCommand({\n      Bucket: config.PRIVATE_BUCKET,\n      Key: invoiceKey(orderId),\n      Body: pdf,\n      ContentType: 'application/pdf',\n      Metadata: { 'order-id': orderId }, // stored as x-amz-meta-order-id\n    }),\n  );\n}\n\n// Short-lived link for a customer who has already been authorized by the API.\nexport function invoiceDownloadUrl({ presigner }: S3Clients, config: Config, orderId: string): Promise<string> {\n  const command = new GetObjectCommand({\n    Bucket: config.PRIVATE_BUCKET,\n    Key: invoiceKey(orderId),\n    ResponseContentDisposition: `attachment; filename=\"pierogi-${orderId}.pdf\"`,\n  });\n  return getSignedUrl(presigner, command, { expiresIn: 60 });\n}\n\n// Alternative: stream through the API (audit logs, watermarks, no S3 URL exposed).\nexport async function openInvoice({ s3 }: S3Clients, config: Config, orderId: string) {\n  try {\n    const res = await s3.send(new GetObjectCommand({ Bucket: config.PRIVATE_BUCKET, Key: invoiceKey(orderId) }));\n    return { body: res.Body as Readable, contentType: res.ContentType, contentLength: res.ContentLength };\n  } catch (err) {\n    if (err instanceof NoSuchKey) return undefined;\n    throw err;\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"dotnet/S3Demo/Invoices.cs"},"content":[{"type":"text","text":"using Amazon.S3;\nusing Amazon.S3.Model;\n\nnamespace S3Demo;\n\npublic sealed class Invoices(IAmazonS3 s3, string bucket)\n{\n    private static string KeyFor(string orderId) => $\"invoices/{orderId}.pdf\";\n\n    public Task SaveAsync(string orderId, Stream pdf) =>\n        s3.PutObjectAsync(new PutObjectRequest\n        {\n            BucketName = bucket,\n            Key = KeyFor(orderId),\n            InputStream = pdf,\n            ContentType = \"application/pdf\",\n        });\n\n    // A one-minute link for a customer the API has already authorized.\n    public Task<string> DownloadUrlAsync(string orderId) =>\n        s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest\n        {\n            BucketName = bucket,\n            Key = KeyFor(orderId),\n            Verb = HttpVerb.GET,\n            Expires = DateTime.UtcNow.AddMinutes(1),\n            ResponseHeaderOverrides = { ContentDisposition = $\"attachment; filename=\\\"pierogi-{orderId}.pdf\\\"\" },\n        });\n\n    // Streaming through the API: copy S3's response stream without buffering the file.\n    public async Task CopyToAsync(string orderId, Stream destination, CancellationToken ct = default)\n    {\n        using var response = await s3.GetObjectAsync(bucket, KeyFor(orderId), ct);\n        await response.ResponseStream.CopyToAsync(destination, ct);\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/invoices.py"},"content":[{"type":"text","text":"from typing import BinaryIO\n\nfrom s3_client import PRIVATE_BUCKET, s3\n\n\ndef _key(order_id: str) -> str:\n    return f\"invoices/{order_id}.pdf\"\n\n\ndef save_invoice(order_id: str, pdf: bytes) -> None:\n    s3.put_object(Bucket=PRIVATE_BUCKET, Key=_key(order_id), Body=pdf, ContentType=\"application/pdf\")\n\n\ndef invoice_download_url(order_id: str) -> str:\n    \"\"\"A one-minute link for a customer the API has already authorized.\"\"\"\n    return s3.generate_presigned_url(\n        \"get_object\",\n        Params={\n            \"Bucket\": PRIVATE_BUCKET,\n            \"Key\": _key(order_id),\n            \"ResponseContentDisposition\": f'attachment; filename=\"pierogi-{order_id}.pdf\"',\n        },\n        ExpiresIn=60,\n    )\n\n\ndef copy_invoice_to(order_id: str, destination: BinaryIO) -> None:\n    \"\"\"Stream through the API without loading the whole file into memory.\"\"\"\n    body = s3.get_object(Bucket=PRIVATE_BUCKET, Key=_key(order_id))[\"Body\"]\n    for chunk in body.iter_chunks(chunk_size=64 * 1024):\n        destination.write(chunk)"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Presigned GET with a 302 redirect","marks":[{"type":"bold"}]},{"type":"text","text":" – 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. "},{"type":"text","text":"ResponseContentDisposition","marks":[{"type":"code"}]},{"type":"text","text":" forces a download with a nice file name."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Streaming through the API","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"pipeline(body, res)","marks":[{"type":"code"}]},{"type":"text","text":") – when you want to log every download, add a watermark or hide S3 addresses. It costs server transfer, but memory stays constant."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"NoSuchKey","marks":[{"type":"code"}]},{"type":"text","text":" is an error class in the SDK – catch it and turn it into a 404 instead of letting a 500 through."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"A presigned URL is a bearer ticket"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Whoever has the link downloads the file – no login, until it expires. Keep the lifetime short (seconds to minutes), generate links only after authorization, and keep them out of logs and analytics. A signature made with a role's temporary credentials stops working when those credentials expire at the latest, even if "},{"type":"text","text":"expiresIn","marks":[{"type":"code"}]},{"type":"text","text":" was longer."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-7-large-files-multipart-upload"},"content":[{"type":"text","text":"Step 7. Large files: multipart upload"}]},{"type":"paragraph","content":[{"type":"text","text":"A single "},{"type":"text","text":"PutObject","marks":[{"type":"code"}]},{"type":"text","text":" accepts at most 5 GB, and a dropped connection means starting over. Multipart splits the file into parts sent in parallel, retrying individual parts."}]},{"type":"codeGroup","attrs":{"title":"Nightly export and paginated listing (Node.js, C#, Python)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/exports.ts"},"content":[{"type":"text","text":"import { createReadStream } from 'node:fs';\nimport { paginateListObjectsV2, type _Object } from '@aws-sdk/client-s3';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport type { Config } from './config.js';\nimport type { S3Clients } from './s3.js';\n\n// Multipart upload of a large file: parts in parallel, retries per part, constant memory.\nexport async function uploadDailyExport({ s3 }: S3Clients, config: Config, filePath: string, signal?: AbortSignal) {\n  const key = `exports/${new Date().toISOString().slice(0, 10)}.csv.gz`;\n  const upload = new Upload({\n    client: s3,\n    params: { Bucket: config.PRIVATE_BUCKET, Key: key, Body: createReadStream(filePath), ContentType: 'application/gzip' },\n    partSize: 16 * 1024 * 1024, // min 5 MiB, max 10,000 parts per object\n    queueSize: 4, // parts uploaded concurrently\n    leavePartsOnError: false, // abort the multipart upload on failure\n  });\n  upload.on('httpUploadProgress', ({ loaded, total }) => {\n    console.info(`export ${key}: ${loaded ?? 0}/${total ?? '?'} bytes`);\n  });\n  signal?.addEventListener('abort', () => void upload.abort());\n  await upload.done();\n  return key;\n}\n\n// Paginated listing – a single ListObjectsV2 call returns at most 1,000 keys.\nexport async function listExports({ s3 }: S3Clients, config: Config): Promise<_Object[]> {\n  const objects: _Object[] = [];\n  for await (const page of paginateListObjectsV2({ client: s3 }, { Bucket: config.PRIVATE_BUCKET, Prefix: 'exports/' })) {\n    objects.push(...(page.Contents ?? []));\n  }\n  return objects;\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"dotnet/S3Demo/Exports.cs"},"content":[{"type":"text","text":"using Amazon.S3;\nusing Amazon.S3.Model;\nusing Amazon.S3.Transfer;\n\nnamespace S3Demo;\n\npublic sealed class Exports(IAmazonS3 s3, string bucket)\n{\n    // TransferUtility switches to multipart automatically for large files.\n    public async Task<string> UploadDailyAsync(string filePath, CancellationToken ct = default)\n    {\n        var key = $\"exports/{DateTime.UtcNow:yyyy-MM-dd}.csv.gz\";\n        var request = new TransferUtilityUploadRequest\n        {\n            BucketName = bucket,\n            Key = key,\n            FilePath = filePath,\n            ContentType = \"application/gzip\",\n            PartSize = 16 * 1024 * 1024,\n        };\n        request.UploadProgressEvent += (_, e) => Console.WriteLine($\"{key}: {e.TransferredBytes}/{e.TotalBytes} bytes\");\n\n        using var transfer = new TransferUtility(s3);\n        await transfer.UploadAsync(request, ct);\n        return key;\n    }\n\n    // Paginator: ListObjectsV2 returns at most 1,000 keys per call.\n    public async Task<List<string>> ListAsync(CancellationToken ct = default)\n    {\n        var keys = new List<string>();\n        var pages = s3.Paginators.ListObjectsV2(new ListObjectsV2Request { BucketName = bucket, Prefix = \"exports/\" });\n        await foreach (var page in pages.Responses.WithCancellation(ct))\n            keys.AddRange((page.S3Objects ?? []).Select(o => o.Key));\n        return keys;\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/exports.py"},"content":[{"type":"text","text":"from datetime import date\n\nfrom boto3.s3.transfer import TransferConfig\n\nfrom s3_client import PRIVATE_BUCKET, s3\n\n# upload_file switches to multipart above the threshold and uploads parts in parallel.\nTRANSFER = TransferConfig(multipart_threshold=16 * 1024 * 1024, multipart_chunksize=16 * 1024 * 1024, max_concurrency=4)\n\n\ndef upload_daily_export(file_path: str) -> str:\n    key = f\"exports/{date.today().isoformat()}.csv.gz\"\n    s3.upload_file(\n        file_path,\n        PRIVATE_BUCKET,\n        key,\n        ExtraArgs={\"ContentType\": \"application/gzip\"},\n        Config=TRANSFER,\n        Callback=lambda sent: print(f\"{key}: +{sent} bytes\"),\n    )\n    return key\n\n\ndef list_exports() -> list[str]:\n    \"\"\"The paginator follows continuation tokens – one call returns at most 1,000 keys.\"\"\"\n    keys: list[str] = []\n    for page in s3.get_paginator(\"list_objects_v2\").paginate(Bucket=PRIVATE_BUCKET, Prefix=\"exports/\"):\n        keys.extend(obj[\"Key\"] for obj in page.get(\"Contents\", []))\n    return keys"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Upload","marks":[{"type":"code"}]},{"type":"text","text":" from "},{"type":"text","text":"@aws-sdk/lib-storage","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"TransferUtility","marks":[{"type":"code"}]},{"type":"text","text":" in C#, "},{"type":"text","text":"upload_file","marks":[{"type":"code"}]},{"type":"text","text":" in Python) does everything for you: "},{"type":"text","text":"CreateMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":", parallel "},{"type":"text","text":"UploadPart","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"CompleteMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":", and "},{"type":"text","text":"AbortMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" on failure. A file stream means constant memory use – roughly "},{"type":"text","text":"partSize × queueSize","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"callout","attrs":{"variant":"danger","title":"Unfinished uploads cost money"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An interrupted multipart upload that nobody completed or aborted leaves invisible parts in the bucket – you will not see them in "},{"type":"text","text":"ListObjects","marks":[{"type":"code"}]},{"type":"text","text":", but you pay for them like regular data. The "},{"type":"text","text":"AbortIncompleteMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" lifecycle rule (step 9) belongs in every bucket."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-8-cloudfront-in-front-of-s3"},"content":[{"type":"text","text":"Step 8. CloudFront in front of S3"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"codeGroup","attrs":{"title":"Bucket policy for CloudFront (OAC) and signed URLs"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"infra/bucket-policy-cloudfront.json"},"content":[{"type":"text","text":"{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"AllowCloudFrontOriginAccessControl\",\n      \"Effect\": \"Allow\",\n      \"Principal\": { \"Service\": \"cloudfront.amazonaws.com\" },\n      \"Action\": \"s3:GetObject\",\n      \"Resource\": \"arn:aws:s3:::pierogi-media-123456789012/menu/*\",\n      \"Condition\": {\n        \"StringEquals\": { \"AWS:SourceArn\": \"arn:aws:cloudfront::123456789012:distribution/E2EXAMPLE123\" }\n      }\n    }\n  ]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/cdn.ts"},"content":[{"type":"text","text":"import { getSignedUrl } from '@aws-sdk/cloudfront-signer';\n\n// Private content through CloudFront (e.g. recipe videos for paying members):\n// a signed URL checked at the edge, the bucket stays closed behind Origin Access Control.\nexport function signedCdnUrl(path: string, opts: { cdnUrl: string; keyPairId: string; privateKey: string }) {\n  return getSignedUrl({\n    url: `${opts.cdnUrl}/${path}`,\n    keyPairId: opts.keyPairId, // public key id from a CloudFront key group\n    privateKey: opts.privateKey, // PEM from Secrets Manager, never from the repository\n    dateLessThan: new Date(Date.now() + 10 * 60_000).toISOString(),\n  });\n}"}]}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Create a CloudFront distribution with the "},{"type":"text","text":"media","marks":[{"type":"code"}]},{"type":"text","text":" bucket as the origin and "},{"type":"text","text":"Origin Access Control","marks":[{"type":"bold"}]},{"type":"text","text":" (OAC) – CloudFront signs its requests to S3."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Add a bucket policy with "},{"type":"text","text":"Principal: cloudfront.amazonaws.com","marks":[{"type":"code"}]},{"type":"text","text":" and an "},{"type":"text","text":"AWS:SourceArn","marks":[{"type":"code"}]},{"type":"text","text":" condition pointing at your distribution – no other distribution and nobody on the internet can read the objects."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Object keys are immutable ("},{"type":"text","text":"menu/ruskie/<uuid>.webp","marks":[{"type":"code"}]},{"type":"text","text":") and carry "},{"type":"text","text":"Cache-Control: max-age=31536000, immutable","marks":[{"type":"code"}]},{"type":"text","text":" – a new photo = a new key, so you do not need costly cache invalidations."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"For paid content (e.g. pierogi-making videos for club members) use "},{"type":"text","text":"CloudFront signed URLs","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"@aws-sdk/cloudfront-signer","marks":[{"type":"code"}]},{"type":"text","text":") with a key from a key group."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"OAC replaced the older Origin Access Identity (OAI) mechanism – use OAC for new distributions."}]},{"type":"heading","attrs":{"level":2,"id":"step-9-lifecycle-and-storage-classes"},"content":[{"type":"text","text":"Step 9. Lifecycle and storage classes"}]},{"type":"codeGroup","attrs":{"title":"Lifecycle rules for the private bucket"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"infra/lifecycle.json"},"content":[{"type":"text","text":"{\n  \"Rules\": [\n    {\n      \"ID\": \"abort-incomplete-multipart-uploads\",\n      \"Status\": \"Enabled\",\n      \"Filter\": {},\n      \"AbortIncompleteMultipartUpload\": { \"DaysAfterInitiation\": 7 }\n    },\n    {\n      \"ID\": \"exports-to-glacier-then-delete\",\n      \"Status\": \"Enabled\",\n      \"Filter\": { \"Prefix\": \"exports/\" },\n      \"Transitions\": [{ \"Days\": 30, \"StorageClass\": \"GLACIER_IR\" }],\n      \"Expiration\": { \"Days\": 365 }\n    },\n    {\n      \"ID\": \"old-invoices-to-infrequent-access\",\n      \"Status\": \"Enabled\",\n      \"Filter\": { \"Prefix\": \"invoices/\" },\n      \"Transitions\": [{ \"Days\": 90, \"StorageClass\": \"STANDARD_IA\" }]\n    }\n  ]\n}"}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Class"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"For what"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Notes"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 Standard"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"frequently read data (menu photos)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no retrieval fees"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 Intelligent-Tiering"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"unpredictable access"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"moves objects between tiers by itself, small per-object monitoring fee"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 Standard-IA"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"rarely read but needed instantly (old invoices)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"min. 30 days and 128 KB per object, per-GB retrieval fee"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 Glacier Instant Retrieval"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"an archive read once a quarter"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"millisecond reads, min. 90 days"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Glacier Flexible / Deep Archive"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"just in case\" archives"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"restores take minutes to hours (Deep Archive: up to 12 h or more)"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Invoices must be kept for years, so they have no "},{"type":"text","text":"Expiration","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"costs-what-you-pay-for"},"content":[{"type":"text","text":"Costs: what you pay for"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Item"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Approximate price"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Watch out for"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 Standard storage"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.023 per GB-month"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"versioning keeps every version"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"PUT, POST, LIST"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.005 per 1,000 requests"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"millions of small files = many requests"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"GET"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.0004 per 1,000 requests"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 → internet transfer"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.09 per GB (after the free 100 GB/month per account)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"usually the largest item for public files"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S3 → CloudFront transfer"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"USD 0"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"CloudFront has its own price list and a free 1 TB/month tier"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The most common surprises: internet transfer from a public bucket without a CDN, unfinished multipart uploads, old object versions without a "},{"type":"text","text":"NoncurrentVersionExpiration","marks":[{"type":"code"}]},{"type":"text","text":" rule, and LIST requests in a loop every second."}]},{"type":"heading","attrs":{"level":2,"id":"c-and-python-variants"},"content":[{"type":"text","text":"C# and Python variants"}]},{"type":"paragraph","content":[{"type":"text","text":"The C# and Python snippets in steps 4, 6 and 7 form complete mini-projects. Client configuration and entry points:"}]},{"type":"codeGroup","attrs":{"title":"C# (AWSSDK.S3 4.x) and Python (boto3) projects"},"content":[{"type":"codeBlock","attrs":{"language":"xml","filename":"dotnet/S3Demo/S3Demo.csproj"},"content":[{"type":"text","text":"<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  <PropertyGroup>\n    <OutputType>Exe</OutputType>\n    <TargetFramework>net10.0</TargetFramework>\n    <ImplicitUsings>enable</ImplicitUsings>\n    <Nullable>enable</Nullable>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"AWSSDK.S3\" Version=\"4.1.2.1\" />\n  </ItemGroup>\n\n</Project>"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"dotnet/S3Demo/Program.cs"},"content":[{"type":"text","text":"using Amazon;\nusing Amazon.S3;\nusing S3Demo;\n\n// Credentials and region come from the default chain (AWS_PROFILE, env vars, IAM role).\nvar region = RegionEndpoint.GetBySystemName(Environment.GetEnvironmentVariable(\"AWS_REGION\") ?? \"eu-central-1\");\nusing var s3 = new AmazonS3Client(new AmazonS3Config { RegionEndpoint = region });\n\nvar mediaBucket = Environment.GetEnvironmentVariable(\"MEDIA_BUCKET\") ?? \"pierogi-media-123456789012\";\nvar privateBucket = Environment.GetEnvironmentVariable(\"PRIVATE_BUCKET\") ?? \"pierogi-private-123456789012\";\n\nvar upload = await new PhotoUploads(s3, mediaBucket, 5 * 1024 * 1024).CreateAsync(\"ruskie\", \"image/webp\");\nConsole.WriteLine($\"POST {upload.Url} with {upload.Fields.Count} form fields, key {upload.Key}\");\n\nvar link = await new Invoices(s3, privateBucket).DownloadUrlAsync(\"o-42\");\nConsole.WriteLine($\"Invoice link: {link}\");"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":"python/requirements.txt"},"content":[{"type":"text","text":"boto3>=1.44"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/s3_client.py"},"content":[{"type":"text","text":"import os\n\nimport boto3\nfrom botocore.config import Config\n\n# Credentials come from the default chain (AWS_PROFILE, env vars, IAM role) – never from code.\nREGION = os.environ.get(\"AWS_REGION\", \"eu-central-1\")\nMEDIA_BUCKET = os.environ.get(\"MEDIA_BUCKET\", \"pierogi-media-123456789012\")\nPRIVATE_BUCKET = os.environ.get(\"PRIVATE_BUCKET\", \"pierogi-private-123456789012\")\n\ns3 = boto3.client(\n    \"s3\",\n    region_name=REGION,\n    config=Config(\n        signature_version=\"s3v4\",\n        # Regional virtual-hosted URLs (bucket.s3.<region>.amazonaws.com) – the legacy global\n        # endpoint answers with a redirect for buckets outside us-east-1, which breaks browser uploads.\n        s3={\"addressing_style\": \"virtual\"},\n        # Presigned URLs for browsers: no checksum of an empty body inside the URL.\n        request_checksum_calculation=\"when_required\",\n    ),\n)"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/main.py"},"content":[{"type":"text","text":"from invoices import invoice_download_url\nfrom photo_uploads import create_photo_upload\n\nif __name__ == \"__main__\":\n    upload = create_photo_upload(\"ruskie\", \"image/webp\")\n    print(\"POST\", upload[\"url\"], \"fields:\", sorted(upload[\"fields\"]), \"key:\", upload[\"key\"])\n    print(\"Invoice link:\", invoice_download_url(\"o-42\")[:120], \"...\")"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"C#:","marks":[{"type":"bold"}]},{"type":"text","text":" AWSSDK 4.x has async "},{"type":"text","text":"GetPreSignedURLAsync","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"CreatePresignedPostAsync","marks":[{"type":"code"}]},{"type":"text","text":" with "},{"type":"text","text":"S3PostCondition","marks":[{"type":"code"}]},{"type":"text","text":" conditions, and response collections may be "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":" (hence "},{"type":"text","text":"page.S3Objects ?? []","marks":[{"type":"code"}]},{"type":"text","text":"). In ASP.NET Core register the client via "},{"type":"text","text":"AWSSDK.Extensions.NETCore.Setup","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"services.AddAWSService<IAmazonS3>()","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Python:","marks":[{"type":"bold"}]},{"type":"text","text":" set "},{"type":"text","text":"addressing_style: virtual","marks":[{"type":"code"}]},{"type":"text","text":" so boto3 generates regional addresses ("},{"type":"text","text":"bucket.s3.eu-central-1.amazonaws.com","marks":[{"type":"code"}]},{"type":"text","text":"). 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)."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Locally without AWS:","marks":[{"type":"bold"}]},{"type":"text","text":" LocalStack or MinIO emulate the S3 API. In Node set "},{"type":"text","text":"S3_ENDPOINT=http://localhost:4566","marks":[{"type":"code"}]},{"type":"text","text":" (the client gets "},{"type":"text","text":"forcePathStyle: true","marks":[{"type":"code"}]},{"type":"text","text":"), in Python "},{"type":"text","text":"endpoint_url","marks":[{"type":"code"}]},{"type":"text","text":", in C# "},{"type":"text","text":"ServiceURL","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"ForcePathStyle = true","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"common-mistakes"},"content":[{"type":"text","text":"Common mistakes"}]},{"type":"callout","attrs":{"variant":"danger","title":"A public bucket \"just for a moment\""},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"I will turn off Block Public Access so the photos work and fix it later\". A month later someone drops a customer export into that bucket. Serve public content through CloudFront with OAC and keep Block Public Access on at the account level."}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Object keys from user file names","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"../../","marks":[{"type":"code"}]},{"type":"text","text":", non-ASCII characters, collisions and personal data in URLs. Generate your own keys."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Presigned PUT without a size limit","marks":[{"type":"bold"}]},{"type":"text","text":" – someone uploads 5 GB into your bucket and you pay for storing it. Use presigned POST for user uploads."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Creating a new ","marks":[{"type":"bold"}]},{"type":"text","text":"S3Client","marks":[{"type":"code"}]},{"type":"text","text":" per request","marks":[{"type":"bold"}]},{"type":"text","text":" – no connection pool and a credential lookup every time."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Reading ","marks":[{"type":"bold"}]},{"type":"text","text":"res.Body","marks":[{"type":"code"}]},{"type":"text","text":" into memory","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"transformToByteArray()","marks":[{"type":"code"}]},{"type":"text","text":") for large files – use streams."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"No CORS or ","marks":[{"type":"bold"}]},{"type":"text","text":"AllowedOrigins: [\"*\"]","marks":[{"type":"code"}]},{"type":"text","text":" – the first blocks browser uploads, the second lets any website use your signed forms in victims' browsers."}]}]}]},{"type":"prosCons","attrs":{"pros":["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"],"cons":["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"],"prosTitle":"S3 as file storage","consTitle":"S3 limitations"}},{"type":"heading","attrs":{"level":2,"id":"check-yourself"},"content":[{"type":"text","text":"Check yourself"}]},{"type":"quiz","attrs":{"question":"The cook uploads photos from the browser, 5 MB max. Which approach enforces the limit on the S3 side?","multiple":false,"options":[{"text":"Presigned PUT with `expiresIn: 60`","correct":false,"explanation":"A short lifetime does not limit the size – a lot of data fits into a minute."},{"text":"Presigned POST with a `content-length-range` condition","correct":true,"explanation":"Yes – S3 rejects a file outside the range before storing it."},{"text":"Checking `file.size` in JavaScript before sending","correct":false,"explanation":"That is only a convenience for the user – an attacker bypasses browser code."}]}},{"type":"quiz","attrs":{"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?","multiple":false,"options":[{"text":"The SDK put an `x-amz-checksum-crc32` computed from an empty body into the URL","correct":true,"explanation":"Yes – sign with a client configured with `requestChecksumCalculation: 'WHEN_REQUIRED'`."},{"text":"No SSE-S3 encryption on the bucket","correct":false,"explanation":"Encryption is the default and does not affect checksums."},{"text":"Too short `expiresIn`","correct":false,"explanation":"An expired link gives an `AccessDenied` error saying it expired, not a checksum error."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how would you design large file uploads from users to S3?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"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: "},{"type":"text","text":"CreateMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" on the server, presigned "},{"type":"text","text":"UploadPart","marks":[{"type":"code"}]},{"type":"text","text":" for the client, "},{"type":"text","text":"CompleteMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" on the server). The server generates the key. After the upload: "},{"type":"text","text":"HeadObject","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"AbortIncompleteMultipartUpload","marks":[{"type":"code"}]},{"type":"text","text":" rule, serving through CloudFront. Bonus points for mentioning transfer costs and that a presigned URL carries the signer's permissions."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"what-s-next"},"content":[{"type":"text","text":"What's next"}]},{"type":"linkCard","attrs":{"url":"/en/articles/aws-sqs","title":"Amazon SQS","description":"Processing photos and orders in the background with a queue","kind":"article","ref":"aws-sqs"}},{"type":"linkCard","attrs":{"url":"/en/articles/aws-ses","title":"Amazon SES","description":"Sending the invoice link to the customer by e-mail","kind":"article","ref":"aws-ses"}},{"type":"linkCard","attrs":{"url":"/en/articles/authentication","title":"Login and registration","description":"Authorization before issuing a presigned URL","kind":"article","ref":"authentication"}},{"type":"linkCard","attrs":{"url":"/en/topics/aws-s3","title":"AWS S3","description":"Everything about S3","kind":"topic","ref":"aws-s3"}}]},"toc":[{"id":"step-1-buckets-with-safe-settings","text":"Step 1. Buckets with safe settings","level":2,"locked":false},{"id":"step-2-the-project-and-s3-clients","text":"Step 2. The project and S3 clients","level":2,"locked":false},{"id":"step-3-iam-the-least-privilege-possible","text":"Step 3. IAM: the least privilege possible","level":2,"locked":false},{"id":"step-4-browser-uploads-presigned-post","text":"Step 4. Browser uploads: presigned POST","level":2,"locked":false},{"id":"step-5-the-browser-and-api-routes","text":"Step 5. The browser and API routes","level":2,"locked":false},{"id":"step-6-downloads-a-short-link-or-streaming","text":"Step 6. Downloads: a short link or streaming","level":2,"locked":false},{"id":"step-7-large-files-multipart-upload","text":"Step 7. Large files: multipart upload","level":2,"locked":false},{"id":"step-8-cloudfront-in-front-of-s3","text":"Step 8. CloudFront in front of S3","level":2,"locked":false},{"id":"step-9-lifecycle-and-storage-classes","text":"Step 9. Lifecycle and storage classes","level":2,"locked":false},{"id":"costs-what-you-pay-for","text":"Costs: what you pay for","level":2,"locked":false},{"id":"c-and-python-variants","text":"C# and Python variants","level":2,"locked":false},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":false},{"id":"check-yourself","text":"Check yourself","level":2,"locked":false},{"id":"what-s-next","text":"What's next","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":69,"visibleBlocks":69,"resources":[{"id":"6b0857b53c96f2d34d0b3a22","type":"article","provider":"web","url":"https://www.allthingsdistributed.com/2021/04/s3-strong-consistency.html","embedUrl":null,"title":"Diving Deep on S3 Consistency","description":"A deep dive on why we changed Amazon S3's consistency model","author":"All Things Distributed","thumbnailUrl":"https://www.allthingsdistributed.com/images/images/s3151.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2021-04-28T12:36:43.000Z","popularity":61,"verifiedAt":"2026-11-26T11:19:38.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857b73c96f2d34d0b3b7a","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/how-aws-s3-is-built/id1769051199?i=1000746086683","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1769051199?i=1000746086683","title":"How AWS S3 is built","description":"Brought to You By: • Statsig — ⁠ The unified platform for flags, analytics, experiments, and more. • Sonar – The makers of SonarQube, the industry standard for automated code review • WorkOS – Everything you need to make your app enterprise ready. — Amazon S3 is one of the largest distributed…","author":"The Pragmatic Engineer","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/3b/0f/ca/3b0fca12-abd1-e894-47d6-18955a57412c/mza_17031005183204943468.jpg/600x600bb.jpg","durationSec":4694,"lang":"en","topics":[],"techs":["general"],"tags":["podcast","system-design","distributed-systems","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2026-01-21T18:00:17.000Z","popularity":72,"verifiedAt":"2026-11-26T11:04:25.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:53.924Z","updatedAt":"2026-11-26T16:00:53.924Z"},{"id":"6b0857c23c96f2d34d0b451e","type":"article","provider":"web","url":"https://event-driven.io/en/show-me-the-money-practically-navigating","embedUrl":null,"title":"Show me the money! Practically navigating the Cloud Costs Complexity - Event-Driven.io","description":"In my last article, I explored how Amazon S3’s new conditional writes feature can be used to implement a strongly consistent event store. I think that this feature opens…","author":"Oskar Dudycz (event-driven.io)","thumbnailUrl":"https://event-driven.io/_astro/2024-09-09-cover.DAbbuKGs_Z2cdXzj.jpg","durationSec":null,"lang":"en","topics":["event-sourcing","event-driven-architecture"],"techs":["general"],"tags":["event-sourcing","cloud","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-09-09T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:28:22.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857b33c96f2d34d0b37f4","type":"article","provider":"web","url":"https://blog.cloudflare.com/introducing-r2-object-storage","embedUrl":null,"title":"Cloudflare R2 storage: Rapid and reliable object storage, minus the egress fees","description":"Introducing Cloudflare’s S3-compatible Object Storage service, with zero egress bandwidth charges and automatic migration from S3-compatible services.","author":"Cloudflare Blog","thumbnailUrl":"https://blog.cloudflare.com/_emdash/api/media/file/01KW469E3KRDBEK9ZT4D9P0TG7.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2021-09-28T13:01:00.000Z","popularity":81,"verifiedAt":"2026-11-26T11:19:35.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.221Z","updatedAt":"2026-11-26T16:00:51.221Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}