%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Short(["Memory runs short"])
Once{"One time job?<br/><em>a build, a compile</em>"}
Swap("Add swap space<br/><em>same instance type</em><br/><em>slower, gone after reboot</em>")
Size("Change the instance type<br/><em>stop, resize, start</em><br/><em>new IP, costs more per hour</em>")
Done(["Job finishes"])
Short --> Once
Once -->|"Yes"| Swap
Once -->|"No, ongoing"| Size
Swap --> Done
Size --> Done
Instance Size
The t3.micro we’ve used since Lab 7 has 1 GiB of RAM and an 8 GiB disk. What can we do when one of them runs short? Lab 11 showed that memory usually runs out first, so we’ll try both fixes on the real instance: swap space for a one time build, and a larger instance type.
Then we’ll grow the disk, which turns out to be a separate change from the instance type.
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
subgraph Type["<strong>Instance type</strong>"]
Micro("t3.micro<br/><em>2 vCPUs, 1 GiB RAM</em>")
Small("t3.small<br/><em>2 vCPUs, 2 GiB RAM</em>")
Micro -->|"stop, modify, start"| Small
end
subgraph Vol["<strong>EBS volume</strong>"]
Eight[("8 GiB")]
Sixteen[("16 GiB")]
Eight -->|"modify-volume, growpart,<br/>xfs_growfs (no stop)"| Sixteen
end
Type -.-|"attached to"| Vol
When a build runs out of memory
Compiling anything from source, not just Python (see App Dependencies), is memory hungry in a way normal application workloads aren’t. t3.micro gives you 1 GB of RAM, and a make step that dies partway through with an out of memory error is that limit, not a broken source tree.
There are two ways around the limit, and each trades off differently:
Add swap (one time jobs): swap space lets the kernel page memory out to disk instead of killing the process, so the build finishes on the original instance type. It’s slower under memory pressure than real RAM would be, but for a one time build that’s a fine trade, and it avoids touching the instance’s configuration at all.
Change the instance type (ongoing needs): stop the instance, change the type to one with more RAM, and start it back up. This costs a few minutes of downtime, a new public IP, and more spend for every hour it runs, so it fits work that keeps needing the memory (an app or a model that runs every day). For a one time build, we can still size up temporarily and size back down afterward.
To add swap, create a 2 GB file, restrict it to root, format it as swap, and turn it on:
sudo fallocate -l 2G /swapfilesudo chmod 600 /swapfileOnly mkswap prints anything; the other three commands are silent when they succeed:
sudo mkswap /swapfileSetting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=df81d2e4-e6cb-4eec-8ac4-7583eef1a0e6sudo swapon /swapfileWe can confirm the kernel is using it with free -h. The Swap: row should now show a total of about 2.0Gi:
free -h total used free shared buff/cache available
Mem: 911Mi 327Mi 153Mi 69Mi 431Mi 372Mi
Swap: 2.0Gi 0B 2.0GiBuilding the R API with swap
App Dependencies ran the Python penguin API from S3 but stopped short of the R API: compiling its renv.lock packages ran the t3.micro out of memory, and the instance stopped responding to SSH until we stopped and started it. With swap turned on, we can finish that build.
From the root of the do4ds-labs repo on the local machine, copy the script, the lockfile, and the files renv uses to bootstrap itself into the ~/penguin-api/r folder we created in App Dependencies. We skip renv/library, because the packages in it were built for macOS:
scp -i ~/.ssh/aws-dev.pem \
_labs/lab07/R/plumber.R \
_labs/lab07/R/renv.lock \
_labs/lab07/R/.Rprofile \
ec2-user@YOUR_PUBLIC_IP_ADDRESS:~/penguin-api/r/plumber.R 100% 8986 139.6KB/s 00:00
renv.lock 100% 203KB 663.0KB/s 00:00
.Rprofile 100% 26 0.4KB/s 00:00scp -i ~/.ssh/aws-dev.pem \
_labs/lab07/R/renv/activate.R \
_labs/lab07/R/renv/settings.json \
ec2-user@YOUR_PUBLIC_IP_ADDRESS:~/penguin-api/r/renv/activate.R 100% 39KB 318.3KB/s 00:00
settings.json 100% 466 7.4KB/s 00:00Back on the instance, some of the packages in renv.lock compile against system libraries we haven’t installed yet: ragg, textshaping, and systemfonts need the font and image libraries, sodium needs libsodium, and fs needs libuv. nanonext builds its own networking libraries with cmake, and waysign (which plumber2 needs for routing) is written in Rust, so it needs rust and cargo. AL2023 doesn’t install any of these by default:
sudo dnf install -y freetype-devel fontconfig-devel harfbuzz-devel \
fribidi-devel libpng-devel libtiff-devel libjpeg-turbo-devel \
libwebp-devel libsodium-devel libuv-devel cmake rust cargoThe .Rprofile we copied activates renv the first time R starts in this folder, and renv::restore() installs the packages in renv.lock. The lockfile records R 4.6.0 and the instance runs 4.6.1, so renv prints a version warning that’s safe to ignore.
Two settings keep the build inside our memory. renv builds four packages at once by default, and RENV_CONFIG_INSTALL_JOBS=1 makes it build one at a time. exclude = "duckdb" skips the largest build in the lockfile; model.R uses duckdb, but plumber.R doesn’t. Even with both settings, compiling close to 100 packages on a t3.micro with swap takes about 25 to 30 minutes:
cd ~/penguin-api/rRENV_CONFIG_INSTALL_JOBS=1 Rscript -e 'renv::restore(prompt = FALSE, exclude = "duckdb")'✔ reqres 1.2.0 [built from source in 7.5s]
✔ fiery 1.5.0 [built from source in 6.5s]
✔ firesale 0.1.1 [built from source in 3.6s]
✔ routr 2.0.0 [built from source in 6.0s]
✔ fireproof 0.1.0 [built from source in 7.5s]
✔ firesafety 0.1.0 [built from source in 5.0s]
✔ plumber2 0.2.0 [built from source in 9.7s]
Successfully installed 98 packages in 170 seconds.
The dependency tree was repaired during package installation:
- mime [0.13]
- rappdirs [0.3.4]
Call `renv::snapshot()` to capture these dependencies in the lockfile.The 170 seconds in that output comes from a rerun after a first attempt; most packages linked from the renv cache instead of compiling again. mime and rappdirs are dependencies that renv.lock doesn’t record, so renv installed them anyway and suggests a snapshot. We’re only running the API here, so we can leave the lockfile as it is.
pins::board_s3() talks to S3 through the paws.storage package, which isn’t in renv.lock, so we install it into the project library:
Rscript -e 'renv::install("paws.storage")'The following package(s) will be installed:
- httr2 [1.3.0]
- paws.common [0.9.0]
- paws.storage [0.11.0]
- rlang [1.3.0]
These packages will be installed into "~/penguin-api/r/renv/library/linux-amzn-2023/R-4.6/x86_64-pc-linux-gnu".
# Downloading packages -------------------------------------------------------
✔ paws.storage 0.11.0 [669 kB in 45s]
✔ httr2 1.3.0 [302 kB in 45s]
✔ paws.common 0.9.0 [177 kB in 45s]
✔ rlang 1.3.0 [784 kB in 49s]
Successfully downloaded 4 packages in 0.3 seconds.
# Installing packages --------------------------------------------------------
✔ rlang 1.3.0 [built from source in 18s]
✔ httr2 1.3.0 [built from source in 11s]
✔ paws.common 0.9.0 [built from source in 52s]
✔ paws.storage 0.11.0 [built from source in 33s]
Successfully installed 4 packages in 110 seconds.plumber.R reads the same USE_S3 variable as the Python API and starts the API itself, so Rscript is all it takes:
export USE_S3=true
Rscript plumber.R- One or more packages recorded in the lockfile are not installed.
- Use `renv::status()` for more details.
Warning: ‘timedatectl’ indicates the non-existent timezone name ‘n/a’
Warning: Your system is mis-configured: ‘/etc/localtime’ is not a symlink
Warning: It is strongly recommended to set envionment variable TZ to ‘Etc/UCT’ (or equivalent)
Loading from S3: penguin-vetiver-model-data/R/models/
=== Model Loaded Successfully ===
Model name: penguin_lab07_model
Model class: butchered_lm lm
Prototype (expected input):
# A tibble: 0 × 3
# ℹ 3 variables: bill_length_mm <dbl>, species <fct>, sex <fct>
Factor levels:
species: Adelie, Chinstrap, Gentoo
sex: female, male
=================================
Creating default route in request router
╔════════════════════════════════════════════════════════╗
║ Penguin Mass Predictor API ║
╚════════════════════════════════════════════════════════╝
🚀 Starting API server on http://127.0.0.1:8080
📖 Documentation:
Swagger UI: http://127.0.0.1:8080/__docs__/
ReDoc: http://127.0.0.1:8080/__docs__/?redoc=1
🔍 Available endpoints:
Health Checks:
GET /ping - Basic health check
GET /health - Detailed health check
Model Information:
GET /model-info - Model metadata
GET /model-prototype - Expected input format
GET /input-schema - Input documentation
Predictions:
POST /predict - Single/batch prediction
POST /predict-validated - Prediction with validation
POST /predict-batch - Batch predictions
📊 Model Information:
Name: penguin_lab07_model
Version: 20261115T054536Z-54566
Type: butchered_lm
✨ Ready to serve predictions!
plumber2 server started at http://0.0.0.0:8080The lines above the model output aren’t errors. The lockfile message refers to duckdb, which we excluded. The three timezone warnings appear because /etc/localtime on the instance is a file, not a symlink; export TZ=Etc/UTC before Rscript silences them.
We can confirm the API is serving the model from a second SSH session:
curl http://127.0.0.1:8080/ping{"status":["alive"],"timestamp":["2026-12-02 21:44:50"]}Stop the API with Ctrl + C. The packages are compiled now, so the R API runs without the swap file.
The swap file only lasts until the next reboot. After the build finishes, I turn it off and remove the file:
sudo swapoff /swapfilesudo rm /swapfileRunning free -h again confirms the Swap: row is back to zero:
free -h total used free shared buff/cache available
Mem: 911Mi 323Mi 375Mi 0.0Ki 212Mi 451Mi
Swap: 0B 0B 0BEither way, this is a build-time problem, not a runtime one. Once the compiled artifact exists, running it day to day doesn’t need the extra headroom.
Step 1: Confirm the current server size
Before changing anything, we record what the t3.micro has now. Log in to the instance (see SSH config for the awsdev shortcut) and check the CPU, memory, and root volume:
lscpu | grep -E '^(Model name|CPU\(s\)|Thread|Core|Socket)'CPU(s): 2
Model name: Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
Thread(s) per core: 2
Core(s) per socket: 1
Socket(s): 1nproc2free -h total used free shared buff/cache available
Mem: 911Mi 322Mi 160Mi 69Mi 429Mi 377Mi
Swap: 0B 0B 0BThe t3.micro is sold with 1 GiB of RAM, but free -h reports 911Mi because the kernel reserves some memory before it starts counting. Only about 377Mi is available for anything new we start.
df -h /Filesystem Size Used Avail Use% Mounted on
/dev/nvme0n1p1 8.0G 4.9G 3.1G 62% /lscpu separates threads from cores. AWS counts each hardware thread as a vCPU, so CPU(s) and nproc report 2 even though the t3.micro has one physical core (see Cores in Lab 11).
Step 2: Change the instance type and bring it back
The instance type can only change while the instance is stopped. The commands below run on our local machine, not on the instance. First we look up the instance ID by the instance’s Name tag (dev-al2023, from Upgrade to Amazon Linux 2023) and store it in a shell variable:
INSTANCE_ID=$(aws ec2 describe-instances --profile dev-deploy \
--filters Name=tag:Name,Values=dev-al2023 \
--query 'Reservations[].Instances[].InstanceId' \
--output text)
echo "$INSTANCE_ID"i-0514a57a209efcf56echo should print a single ID that starts with i-. If it prints nothing, check the tag name in the EC2 console. The variable lasts until the terminal closes, and Step 4 and “Sizing back down” use it too. Next we stop the instance:
aws ec2 stop-instances --instance-ids "$INSTANCE_ID" --profile dev-deploy
aws ec2 wait instance-stopped --instance-ids "$INSTANCE_ID" --profile dev-deploystop-instances prints the state change (running to stopping). wait instance-stopped prints nothing; it just returns once the instance has fully stopped:
{
"StoppingInstances": [
{
"InstanceId": "i-0514a57a209efcf56",
"CurrentState": {
"Code": 64,
"Name": "stopping"
},
"PreviousState": {
"Code": 16,
"Name": "running"
}
}
]
}With the instance stopped, we change the type to t3.small (2 vCPUs, 2 GiB of RAM) and start it again:
aws ec2 modify-instance-attribute --instance-id "$INSTANCE_ID" \
--instance-type '{"Value": "t3.small"}' --profile dev-deploy
aws ec2 start-instances --instance-ids "$INSTANCE_ID" --profile dev-deploy
aws ec2 wait instance-running --instance-ids "$INSTANCE_ID" --profile dev-deploymodify-instance-attribute and wait instance-running print nothing when they succeed. start-instances shows the instance moving from stopped to pending:
{
"StartingInstances": [
{
"InstanceId": "i-0514a57a209efcf56",
"CurrentState": {
"Code": 0,
"Name": "pending"
},
"PreviousState": {
"Code": 80,
"Name": "stopped"
}
}
]
}The instance gets a new public IP when it starts, so HostName in ~/.ssh/config is now stale. awsdev looks up the new address for us.
A larger type costs more for every hour it runs. We keep the t3.small anyway, for reasons covered in Staying on a t3.small.
Step 3: Confirm the new server size
Back on the instance, we run the same checks as Step 1:
lscpu | grep -E '^(Model name|CPU\(s\)|Thread|Core|Socket)'CPU(s): 2
Model name: Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
Thread(s) per core: 2
Core(s) per socket: 1
Socket(s): 1The CPU is identical: the same Xeon model, one core, and two threads. A t3.small has the same 2 vCPUs as a t3.micro.
nproc2free -h total used free shared buff/cache available
Mem: 1.9Gi 319Mi 1.1Gi 0.0Ki 456Mi 1.4Gi
Swap: 0B 0B 0BMemory is the only thing that changed. Total RAM went from 911Mi to 1.9Gi, and available went from 377Mi to 1.4Gi, nearly four times the room for new work.
df -h /Filesystem Size Used Avail Use% Mounted on
/dev/nvme0n1p1 8.0G 4.9G 3.1G 62% /The root volume is unchanged (8.0G, 62% used), because storage lives on the EBS volume, not the instance type.
Step 4: Upgrade storage (maybe)
Changing the instance type doesn’t change storage. The root EBS volume is separate from the instance, so it keeps its size (and its data) through Step 2. If df -h / shows the disk filling up, we can grow the volume without stopping the instance. First we find the volume’s ID and current size:
aws ec2 describe-volumes --profile dev-deploy \
--filters Name=attachment.instance-id,Values="$INSTANCE_ID" \
--query 'Volumes[].[VolumeId,Size]' --output textThe root volume is 8 GiB:
vol-0ff94e05e8e4fbf44 8Then we set the new size in GiB. A volume can grow but never shrink, and each GiB adds to the monthly bill:
aws ec2 modify-volume --volume-id YOUR_VOLUME_ID --size 16 --profile dev-deploymodify-volume returns right away with the change in the modifying state. The type (gp3), IOPS, and throughput stay the same; only the size goes from 8 to 16:
{
"VolumeModification": {
"VolumeId": "vol-0ff94e05e8e4fbf44",
"ModificationState": "modifying",
"TargetSize": 16,
"TargetIops": 3000,
"TargetVolumeType": "gp3",
"TargetThroughput": 125,
"TargetMultiAttachEnabled": false,
"OriginalSize": 8,
"OriginalIops": 3000,
"OriginalVolumeType": "gp3",
"OriginalThroughput": 125,
"OriginalMultiAttachEnabled": false,
"Progress": 0,
"StartTime": "2026-11-25T08:47:45+00:00"
}
}On the instance, the partition and the filesystem still use the old size. growpart extends the root partition, and xfs_growfs extends the XFS filesystem that AL2023 uses on /:
sudo growpart /dev/nvme0n1 1CHANGED: partition=1 start=24576 old: size=16752607 end=16777183 new: size=33529823 end=33554399growpart reports the partition’s new size in 512 byte sectors: about 16 GiB, up from 8. If it prints NOCHANGE instead, the volume change hasn’t reached the instance yet; wait a minute and run it again.
sudo xfs_growfs -d /meta-data=/dev/nvme0n1p1 isize=512 agcount=2, agsize=1047040 blks
= sectsz=4096 attr=2, projid32bit=1
= crc=1 finobt=1, sparse=1, rmapbt=0
= reflink=1 bigtime=1 inobtcount=1 nrext64=0
= exchange=0
data = bsize=4096 blocks=2094075, imaxpct=25
= sunit=128 swidth=128 blks
naming =version 2 bsize=16384 ascii-ci=0, ftype=1, parent=0
log =internal log bsize=4096 blocks=16384, version=2
= sectsz=4096 sunit=4 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 2094075 to 4191227The last line is the one that matters: the filesystem now has twice as many 4 KiB blocks. df -h confirms it:
df -h /Filesystem Size Used Avail Use% Mounted on
/dev/nvme0n1p1 16G 5.0G 12G 31% /The root filesystem went from 8.0G (62% used) to 16G (31% used), and the instance never stopped.
Staying on a t3.small
Should we go back to the t3.micro now? Not for this book. The labs ahead add services to the same instance, and each one stays in memory the whole time it runs:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'16px', 'lineColor':'#999999', 'cScale0':'#5B8C5A', 'cScale1':'#2A6F77', 'cScale2':'#1B2A41', 'cScaleLabel0':'#ffffff', 'cScaleLabel1':'#ffffff', 'cScaleLabel2':'#ffffff'}}}%%
timeline
Lab 10 : baseball-trajectory
Lab 12 : nginx
: RStudio Server
: JupyterHub
Lab 14 : nginx adds HTTPS
Step 1 showed only 377Mi available on the t3.micro with just baseball-trajectory running. Accessibility adds RStudio Server and JupyterHub, and every user who signs in starts an R or Python session of their own. Swap won’t cover that, because the services run all day, not once. This is the ongoing need from the first diagram, and the instance type is the fix for it.
A t3.small costs twice as much per hour as a t3.micro. A stopped instance costs nothing for its hours (the EBS volume still bills), so stopping it between sessions saves more than sizing down.
Sizing back down later
When the instance only runs baseball-trajectory again, we can go back to a t3.micro. The commands below run from our local machine and use the INSTANCE_ID shell variable from Step 2. If the terminal has closed since then, rerun the lookup from Step 2 first. Then we repeat the Step 2 commands with the original type:
aws ec2 stop-instances --instance-ids "$INSTANCE_ID" --profile dev-deployaws ec2 wait instance-stopped --instance-ids "$INSTANCE_ID" --profile dev-deployaws ec2 modify-instance-attribute --instance-id "$INSTANCE_ID" \
--instance-type '{"Value": "t3.micro"}' --profile dev-deployaws ec2 start-instances --instance-ids "$INSTANCE_ID" --profile dev-deployaws ec2 wait instance-running --instance-ids "$INSTANCE_ID" --profile dev-deployThe larger EBS volume from Step 4 stays at its new size; only the instance type changes.
Recap
Swap space lets a memory hungry, one time job (like compiling from source) finish on a small instance. It’s slower than RAM, and the swap file only lasts until the next reboot.
Changing the instance type takes a stop and a start, and the instance comes back with a new public IP. Going from
t3.microtot3.smallraised RAM from 911Mi to 1.9Gi; the CPU stayed at 2 vCPUs (one core, two threads).Storage belongs to the EBS volume, not the instance type. The volume can grow while the instance runs (
modify-volume,growpart,xfs_growfs), but it can never shrink.We stay on the
t3.smallbecause the labs ahead keep RStudio Server and JupyterHub running next to the app. It costs twice as much per hour, so stopping the instance between sessions matters more than its size. A larger volume costs more every month, whether the instance runs or not.