Skip to content
Visual explainer 5h to learn 5 steps

S3, RDS & Lambda

Store files, run a managed database and deploy a function.

By Invicly Tech, , in Full DevOps with Python. About 14 minutes to read.

Topic 22 of 34

In short

S3 stores files, RDS runs a managed relational database and Lambda runs code on demand. Together they cover storage, data and event-driven tasks without managing servers.

Explained simply

S3 (Simple Storage Service) keeps files, which AWS calls objects, inside buckets. You do not manage disks or servers: you upload a file under a name (its key) and download it later by the same name. It is used for backups, logs, user uploads, static websites and data for analytics.

Storage gets expensive when nobody cleans it up. Lifecycle rules do the cleaning for you: for example, move logs to a cheaper storage class after 30 days and delete them after a year.

RDS (Relational Database Service) runs a real PostgreSQL or MySQL database for you. AWS installs it, applies patches, takes backups and can keep a standby copy in another availability zone. You still design the tables and write the SQL.

Lambda runs a Python function when something happens, such as a file arriving in S3. There is no server to keep running. You pay only for the time your code actually runs, measured in milliseconds.

Together they make a common pattern: users upload to S3, a Lambda function processes the file, and results are saved in RDS or back in S3. Each piece scales on its own.

Press Play on a diagram to walk through it one step at a time.

CompareThree managed services
S3
  • Object storage for files
  • Pay per GB stored
  • Lifecycle rules move or expire data
  • Public access blocked by default
RDS
  • Managed Postgres or MySQL
  • Backups and patching handled
  • Runs in private subnets
  • Pay per hour while running
Lambda
  • Runs a function per event
  • Up to 15 minutes per run
  • Pay per request and duration
  • No servers to manage
FlowEvent-driven thumbnail job
  1. Step 1
    Upload to S3

    User uploads photo to uploads/ prefix.

  2. Step 2
    S3 event fires

    ObjectCreated notification sent to Lambda.

  3. Step 3
    Lambda runs

    Python handler reads bucket and key from event.

  4. Step 4
    Write result

    Saves thumbnail to a different prefix or bucket.

LayersWhere each piece of the upload app lives
  1. 1
    Users

    Upload with a presigned S3 URL

  2. 2
    S3 bucket

    Regional service, outside your VPC

  3. 3
    Lambda function

    Runs on events; can attach to private subnets

  4. 4
    App on EC2, private subnets

    Reads results and serves the API

  5. 5
    RDS, private subnets

    Port 5432 open only to app and Lambda SGs

MapS3 storage classes by access pattern
How often do you read it?
  • Often
    • S3 Standard
  • About monthly
    • Standard-IA
    • One Zone-IA for re-creatable data
  • Rarely, but need it fast
    • Glacier Instant Retrieval
  • Almost never
    • Glacier Flexible Retrieval
    • Glacier Deep Archive
  • Unknown or changing
    • Intelligent-Tiering

In depth

How S3 really stores your data

S3 is a key-value store, not a file system. The key photos/2026/cat.jpg is one flat name; the slashes only look like folders, and the console groups by prefix to make it feel familiar. Renaming a "folder" means copying every object.

One object can be up to 5 TB. A single PUT upload is limited to 5 GB, so larger files use multipart upload, which the CLI and boto3 do for you automatically above a size threshold. Since December 2020, S3 gives strong read-after-write consistency: once a write succeeds, every read sees it.

S3 is designed for 99.999999999 percent (11 nines) durability by storing data across several AZs. New objects are encrypted at rest by default with SSE-S3, and Block Public Access is on by default for new buckets. Turn on versioning for important buckets: an overwrite or delete then keeps the old version, which saves you from accidents and ransomware.

  • Bucket names are global and part of the URL, so they must be unique and DNS friendly
  • Versioning cannot be turned off once on, only suspended
  • Use presigned URLs to let users upload or download without AWS keys

Storage classes and lifecycle rules

Each object has a storage class. S3 Standard is for data you read often. Standard-IA (infrequent access) is cheaper per GB but charges per GB retrieved and bills at least 30 days and 128 KB per object. Glacier Instant Retrieval suits archives you rarely read but need in milliseconds. Glacier Flexible Retrieval and Glacier Deep Archive are the cheapest, but you must restore an object first, which takes minutes to hours (Deep Archive up to 12 hours for standard restores, with a 180-day minimum). Intelligent-Tiering moves objects between tiers by itself for a small monitoring fee.

A lifecycle rule targets objects by prefix or tag and applies transitions (change class after N days) and expirations (delete after N days). With versioning, add rules for noncurrent versions too, or old versions pile up forever. Always add a rule to abort incomplete multipart uploads after a few days: those hidden parts are billed but never shown in normal listings.

FlowA typical lifecycle for logs/
  1. Step 1
    Day 0: Standard

    Fresh logs, read often while debugging

  2. Step 2
    Day 30: Standard-IA

    Rarely read, cheaper per GB

  3. Step 3
    Day 90: Glacier Flexible

    Archive; restore before reading

  4. Step 4
    Day 365: Expire

    Object deleted automatically

RDS PostgreSQL: what AWS runs for you

When you create an RDS instance you choose the engine version, an instance class such as db.t4g.micro or db.m7g.large, and storage, usually gp3. AWS gives you an endpoint, a DNS name like app-db.abc123.us-east-1.rds.amazonaws.com on port 5432. You never get SSH access to the host.

RDS places the database in a DB subnet group, which must cover at least two AZs; use private subnets. Automated backups keep daily snapshots plus transaction logs for 1 to 35 days, so you can restore to any second in that window (point-in-time recovery). A restore always creates a new instance.

Multi-AZ keeps a synchronous standby in another AZ. If the primary fails, RDS flips the endpoint's DNS to the standby, usually within one to two minutes, so apps must reconnect. Read replicas are different: asynchronous copies you can query to spread read load. Settings such as max_connections live in a parameter group, and minor upgrades run in a maintenance window you choose.

  • Multi-AZ is for availability; read replicas are for read scaling
  • Turn on storage encryption at creation: it cannot be enabled later in place
  • Set deletion protection on production databases

Connecting the app to RDS securely

Three layers keep the database safe. Network: set publicly accessible to no, and let the database security group allow 5432 only from the app's security group. Transport: use TLS. RDS for PostgreSQL 15 and later sets rds.force_ssl to 1 by default, and clients should use sslmode=verify-full with the RDS CA bundle so they also check the server's identity. Credentials: never put the password in code or a Git-tracked file.

The simplest credential option is to let RDS manage the master password in Secrets Manager (the --manage-master-user-password flag), which also rotates it. Your app's role gets secretsmanager:GetSecretValue on that one secret and reads it at startup. Create a separate, less privileged database user for the app rather than using the master user.

Another option is IAM database authentication: the app calls generate_db_auth_token and uses the token as a password; it is valid for 15 minutes. For Lambda, which can open many connections quickly, put RDS Proxy in between to pool them.

SequenceApp startup: fetch secret, then connect over TLS
FastAPI on EC2
Secrets Manager
RDS Postgres
  1. 1GetSecretValue using the instance role
    FastAPI on EC2 to Secrets Manager: GetSecretValue using the instance role
  2. 2JSON with username and password
    Secrets Manager to FastAPI on EC2: JSON with username and password
  3. 3TCP 5432, allowed by app SG rule
    FastAPI on EC2 to RDS Postgres: TCP 5432, allowed by app SG rule
  4. 4TLS handshake, server certificate
    RDS Postgres to FastAPI on EC2: TLS handshake, server certificate
  5. 5Verify cert against RDS CA bundle
    FastAPI on EC2 to FastAPI on EC2: Verify cert against RDS CA bundle
  6. 6Log in as app user, run queries
    FastAPI on EC2 to RDS Postgres: Log in as app user, run queries

Lambda under the hood, and S3 triggers

Lambda runs your handler inside a small execution environment. You set memory from 128 MB to 10,240 MB, and CPU grows with memory. The timeout can be up to 900 seconds (15 minutes). Each environment has /tmp storage, 512 MB by default and configurable up to 10 GB. The first call creates the environment and runs your module's top-level code; this is the cold start. Later calls reuse it, so create boto3 clients and database connections outside the handler.

Code ships as a zip (50 MB zipped for direct upload, 250 MB unzipped including layers) or as a container image up to 10 GB. The function's execution role decides what AWS calls it can make, and CloudWatch Logs receives everything it prints.

S3 calls Lambda asynchronously. If your function raises an error, Lambda retries twice more by default. S3 needs permission to invoke the function, a resource policy added with lambda add-permission. Object keys in the event are URL-encoded, so a space arrives as +; decode with urllib.parse.unquote_plus.

  • Make handlers idempotent: S3 events can be delivered more than once
  • Filter the trigger by prefix and suffix, such as uploads/ and .jpg
  • Use a different output prefix or bucket to avoid infinite loops

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create an S3 bucket with lifecycle rules~1h
  2. 2
    Launch an RDS Postgres instance~1h
  3. 3
    Connect the app to RDS securely~1h
  4. 4
    Deploy a Python Lambda function~1h
  5. 5
    Trigger Lambda from S3 events~1h

Key points

  • Bucket names are globally unique; keep Block Public Access on unless you truly need it.
  • Put RDS in private subnets and allow port 5432 only from the app's security group.
  • Store database passwords in Secrets Manager, not in code or environment files in Git.
  • A Lambda handler receives event and context; keep it small and fast.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import boto3

s3 = boto3.client("s3")

def handler(event, context):
    for record in event["Records"]:
        bucket = record["s3"]["bucket"]["name"]
        key = record["s3"]["object"]["key"]
        size = record["s3"]["object"]["size"]
        print(f"New object {key} ({size} bytes) in {bucket}")
    return {"processed": len(event["Records"])}

A Lambda handler triggered by S3 ObjectCreated events.

Add lifecycle rules to a logs bucket

Step 1: write the rules as JSON. The first rule targets the logs/ prefix, moves objects to Standard-IA at 30 days, to Glacier Flexible Retrieval (API name GLACIER) at 90 days and deletes them at 365 days. The second rule applies to the whole bucket and cleans up unfinished multipart uploads after 7 days. Step 2: apply it with put-bucket-lifecycle-configuration, which replaces any existing rules. Step 3: read it back to confirm. Rules run once a day in the background, so changes are not instant.

bash
cat > lifecycle.json <<'EOF'
{"Rules": [
  {"ID": "logs-tiering", "Status": "Enabled", "Filter": {"Prefix": "logs/"},
   "Transitions": [{"Days": 30, "StorageClass": "STANDARD_IA"},
                   {"Days": 90, "StorageClass": "GLACIER"}],
   "Expiration": {"Days": 365}},
  {"ID": "abort-mpu", "Status": "Enabled", "Filter": {},
   "AbortIncompleteMultipartUpload": {"DaysAfterInitiation": 7}}]}
EOF
aws s3api put-bucket-lifecycle-configuration --bucket acme-logs \
  --lifecycle-configuration file://lifecycle.json
aws s3api get-bucket-lifecycle-configuration --bucket acme-logs

Deploy a Python Lambda and trigger it from S3

Step 1: zip the handler file. Step 2: create the function with a Python runtime, the handler name as file.function, and an execution role that can read the bucket and write logs. Step 3: allow S3 to invoke it, limited to your bucket and account. Step 4: add the bucket notification for ObjectCreated events under uploads/. Step 5: upload a test file and read the output in CloudWatch Logs with aws logs tail.

bash
zip function.zip app.py
aws lambda create-function --function-name thumbs --runtime python3.12 \
  --handler app.handler --zip-file fileb://function.zip --timeout 30 --memory-size 512 \
  --role arn:aws:iam::123456789012:role/thumbs-lambda
aws lambda add-permission --function-name thumbs --statement-id s3-invoke \
  --action lambda:InvokeFunction --principal s3.amazonaws.com \
  --source-arn arn:aws:s3:::acme-photos --source-account 123456789012
aws s3api put-bucket-notification-configuration --bucket acme-photos \
  --notification-configuration '{"LambdaFunctionConfigurations": [{
    "LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:thumbs",
    "Events": ["s3:ObjectCreated:*"],
    "Filter": {"Key": {"FilterRules": [{"Name": "prefix", "Value": "uploads/"}]}}}]}'
aws s3 cp cat.jpg s3://acme-photos/uploads/ && aws logs tail /aws/lambda/thumbs --follow

Quick reference

  • S3 keys are flat names; slashes only look like folders
  • Single PUT max 5 GB, object max 5 TB; the CLI and boto3 switch to multipart for you
  • Always add a lifecycle rule to abort incomplete multipart uploads
  • Standard-IA bills a minimum of 30 days and 128 KB per object
  • RDS backups: 1 to 35 days retention, restore creates a new instance
  • Connect to RDS with sslmode=verify-full and the RDS CA bundle
  • Lambda: 128 MB to 10,240 MB memory, max timeout 900 seconds
  • Decode S3 event keys with urllib.parse.unquote_plus before using them

Common mistakes

  • Lambda writing back to the same bucket prefix that triggers it, causing an endless loop.
  • Making the RDS instance publicly accessible to connect from a laptop.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A Lambda triggered by S3 fails with NoSuchKey for a file named my photo.jpg. What is the likely cause?

Question 2

2What does RDS Multi-AZ give you?

Question 3

3Your S3 bill keeps growing, but listing the bucket shows little data. What is a common hidden cause?

Question 4

4What is the maximum timeout for one Lambda invocation?

Question 5

5Where should the boto3 client be created in a Lambda handler file?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a bucket with Block Public Access fully on and versioning enabled, then upload a file twice and list both versions.

  2. Exercise 2medium

    Create a private, encrypted RDS PostgreSQL instance whose master password is managed by Secrets Manager, then connect with full TLS verification.

  3. Exercise 3hard

    Write a Lambda handler for S3 ObjectCreated events that decodes keys, skips anything not under uploads/, and copies each object to processed/ with the same file name.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is S3 a database?
No. S3 stores whole objects by key and cannot query inside them like SQL. You can scan files with tools such as Athena, but for transactions and indexes use RDS or DynamoDB.
RDS or running PostgreSQL on EC2 myself?
RDS costs a bit more per hour but handles backups, patching, failover and monitoring. Running it on EC2 gives full control (any extension, OS access) but makes you responsible for all of that work.
What is a Lambda cold start and how long is it?
It is the delay when Lambda creates a new execution environment and runs your import code. For small Python functions it is typically a few hundred milliseconds; large dependencies and VPC setup can make it longer.
Can Lambda connect to an RDS database in a private subnet?
Yes. Attach the function to the VPC's private subnets with a security group that the database SG allows. Use RDS Proxy if many concurrent invocations would open too many connections.

Go deeper

ShareXLinkedInWhatsApp