What you will learn
- The three kinds of tests (unit, integration, end-to-end) and what each one catches
- How to write unit tests with JUnit 5, AssertJ and Mockito
- How to test against a real PostgreSQL and Redis with Testcontainers
- How to package the backend and frontend as Docker images
- How to keep secrets out of your code, and deploy Chirp to a server or to AWS
- What to check before real users arrive
Why it matters
"It works on my machine" is where most projects stop. Tests prove the app still works after every change, so you can keep improving it without fear. Docker makes "my machine" and "the server" the same thing. Together they turn a project into something you can actually put in front of people.
Why test at all?
Every time you change code, you might break something that used to work. You could re-check every feature by hand after each change: register, log in, post, follow, like, reply. That takes several minutes and you will soon skip it. An automated test is a small program that does those checks for you, in seconds, the same way every time.
Analogy: a pre-flight checklist
Pilots don't skip the checklist because the plane flew fine yesterday. A test suite is the checklist for your code: boring, quick, and the reason surprises are found on the ground rather than in the air.
The test pyramid
Tests come in three sizes. Small tests are fast and precise but see only one piece. Big tests see the whole system but are slower and, when they fail, tell you less about where the problem is. A healthy project has many small tests and a few big ones. Click a layer:
Click (or tab to) a layer of the pyramid.
| Kind | What it runs | Catches | Chirp's examples |
|---|---|---|---|
| Unit | One class; its collaborators are replaced by fakes (mocks) | Wrong rules and edge cases: "liking twice counts once", "only the author can delete" | JwtServiceTest, PostServiceTest |
| Integration | The real Spring application with a real PostgreSQL and Redis | Wrong SQL, broken migrations, security rules, JSON shape, wiring mistakes | ChirpApiIntegrationTest |
| End-to-end | Everything running, driven from outside like a real user | Problems between the pieces: proxies, ports, headers, the browser | api-test.sh (API), a browser test (this course's own suite) |
An honest story: what tests caught while this course was written
Every code sample in this course was run by an automated test suite before publishing. It failed several times, and each failure was a real bug that reading the code had missed:
- A Docker build broke because a comment was written at the end of a
USERline. Dockerfiles only allow comments on their own line (section Dockerize the backend). - Live notifications silently failed behind nginx: the WebSocket handshake got
403because nginx's$hostdrops the port number (section nginx). - A browser test failed on a race: it clicked "Home" and checked the text before the page had actually changed. That bug was in the test, which also happens.
- Two screen layout problems (a button overflowing its card) were found by looking at automated screenshots.
None of these would have been found by unit tests alone. That is the case for having all three levels.
Unit tests with JUnit 5
A unit test checks one class on its own. We use three libraries that Spring Boot's test starter already includes:
- JUnit 5 finds methods marked
@Testand runs them. - AssertJ gives readable checks:
assertThat(result).isEqualTo(expected). - Mockito creates fake versions ("mocks") of other classes, so a test can say "pretend the database returns this".
Every test follows the same three-part shape, often called given / when / then (or arrange / act / assert): set up the situation, do the one thing being tested, check the result. Look for the blank lines that separate the three parts in the tests below.
Testing JwtService: no Spring, no database
JwtService from chapter 4 only needs a secret and a lifetime, so the test creates it with new. That is the fastest kind of test there is. The tests check the four things that matter about tokens: a good token reads back, and three kinds of bad token are refused.
package com.example.chirp.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.example.chirp.user.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** A plain unit test: no Spring, no database. Runs in milliseconds. */
class JwtServiceTest {
private static final String SECRET = base64("test-secret-that-is-at-least-32-bytes-long");
private final JwtService jwtService = new JwtService(new JwtProperties(SECRET, Duration.ofHours(1)));
@Test
void aTokenWeCreateCanBeReadBack() {
String token = jwtService.createToken(user(42L, "alice"));
assertThat(jwtService.parse(token)).isEqualTo(new AuthUser(42L, "alice"));
}
@Test
void aTokenWithAChangedPayloadIsRejected() {
String[] parts = jwtService.createToken(user(42L, "alice")).split("\\.");
// Pretend to be user 1 by rewriting the payload but keeping the old signature.
String forgedPayload = Base64.getUrlEncoder().withoutPadding()
.encodeToString("{\"sub\":\"1\",\"username\":\"admin\"}".getBytes(StandardCharsets.UTF_8));
String forged = parts[0] + "." + forgedPayload + "." + parts[2];
assertThatThrownBy(() -> jwtService.parse(forged)).isInstanceOf(SignatureException.class);
}
@Test
void aTokenSignedWithAnotherKeyIsRejected() {
JwtService other = new JwtService(new JwtProperties(base64("a-completely-different-secret-of-32-bytes"),
Duration.ofHours(1)));
String token = other.createToken(user(42L, "alice"));
assertThatThrownBy(() -> jwtService.parse(token)).isInstanceOf(SignatureException.class);
}
@Test
void anExpiredTokenIsRejected() {
JwtService shortLived = new JwtService(new JwtProperties(SECRET, Duration.ofSeconds(-1)));
String token = shortLived.createToken(user(42L, "alice"));
assertThatThrownBy(() -> jwtService.parse(token)).isInstanceOf(ExpiredJwtException.class);
}
private static User user(long id, String username) {
User user = new User(username, username + "@example.com", "hash", username);
ReflectionTestUtils.setField(user, "id", id); // normally the database sets the id
return user;
}
private static String base64(String text) {
return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
}
}- The forged-payload test plays the attacker from chapter 2: it rewrites the payload to claim to be user 1 but keeps the old signature. The parser must throw
SignatureException. - The expired test uses a negative lifetime (
Duration.ofSeconds(-1)), so the token is already expired when it is created. No waiting, no flaky timing. ReflectionTestUtils.setFieldsets the privateidthat PostgreSQL would normally assign. It comes fromspring-testand is meant exactly for tests like this.
Testing PostService with Mockito
PostService needs nine collaborators (repositories, the notification service, the cache…). For a unit test we don't want a database at all, so every collaborator is a @Mock, and @InjectMocks builds a real PostService that receives those mocks through its constructor.
package com.example.chirp.post;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.notification.NotificationService;
import com.example.chirp.notification.NotificationType;
import com.example.chirp.upload.UploadService;
import com.example.chirp.user.ProfileCache;
import com.example.chirp.user.User;
import com.example.chirp.user.UserRepository;
import com.example.chirp.user.UserService;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.server.ResponseStatusException;
/** Unit test with Mockito: the repositories are fakes, so we test PostService's own rules only. */
@ExtendWith(MockitoExtension.class)
class PostServiceTest {
@Mock PostRepository posts;
@Mock UserRepository users;
@Mock UserService userService;
@Mock LikeRepository likes;
@Mock RepostRepository reposts;
@Mock NotificationService notifications;
@Mock ProfileCache profileCache;
@Mock UploadService uploads;
@Mock ApplicationEventPublisher events;
@InjectMocks PostService postService;
private final AuthUser bob = new AuthUser(2L, "bob");
private Post alicesPost;
@BeforeEach
void setUp() {
User alice = new User("alice", "alice@example.com", "hash", "Alice");
ReflectionTestUtils.setField(alice, "id", 1L);
alicesPost = new Post(alice, "Hello", null);
ReflectionTestUtils.setField(alicesPost, "id", 10L);
}
@Test
void theFirstLikeIsCountedAndTheAuthorIsNotified() {
when(posts.findById(10L)).thenReturn(Optional.of(alicesPost));
when(likes.add(2L, 10L)).thenReturn(true);
when(posts.findLikeCount(10L)).thenReturn(1);
LikeResponse result = postService.like(bob, 10L);
assertThat(result).isEqualTo(new LikeResponse(true, 1));
verify(posts).addToLikeCount(10L, 1);
verify(notifications).notify(1L, 2L, NotificationType.LIKE, 10L);
}
@Test
void likingAgainChangesNothing() {
when(posts.findById(10L)).thenReturn(Optional.of(alicesPost));
when(likes.add(2L, 10L)).thenReturn(false); // the row already exists
when(posts.findLikeCount(10L)).thenReturn(1);
LikeResponse result = postService.like(bob, 10L);
assertThat(result.likeCount()).isEqualTo(1);
verify(posts, never()).addToLikeCount(anyLong(), anyInt());
verifyNoInteractions(notifications);
}
@Test
void onlyTheAuthorCanDeleteAPost() {
when(posts.findById(10L)).thenReturn(Optional.of(alicesPost));
assertThatExceptionOfType(ResponseStatusException.class)
.isThrownBy(() -> postService.delete(bob, 10L))
.extracting(ResponseStatusException::getStatusCode)
.isEqualTo(HttpStatus.FORBIDDEN);
verify(posts, never()).delete(any());
}
@Test
void pageSizeIsKeptBetweenOneAndFifty() {
assertThat(PostService.pageSize(0)).isEqualTo(1);
assertThat(PostService.pageSize(20)).isEqualTo(20);
assertThat(PostService.pageSize(10_000)).isEqualTo(50);
}
}Read the first test as a sentence: given post 10 exists and adding the like inserts a new row, when Bob likes it, then the answer is "liked, count 1", the counter was incremented once, and Alice was notified. The second test is the important edge case from chapter 1: when likes.add returns false (the row already exists), verify(posts, never()).addToLikeCount(…) proves the counter was not touched and nobody was notified.
Mockito is strict, which is a good thing
MockitoExtension fails a test that stubs something it never uses (UnnecessaryStubbingException). That keeps tests honest: every when(…) line must matter. If you see this error, delete the unused stub rather than switching strictness off.
Running the tests
From the backend folder, run every test, or just one class while you work on it:
# every test (unit + integration; needs Docker running for the integration test)
./mvnw test
# just one class, for a quick loop while you work on PostService
./mvnw test -Dtest=PostServiceTestMaven prints one line per test class and a summary at the end. All of Chirp's backend tests pass:
[INFO] Running com.example.chirp.post.PostServiceTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.168 s -- in com.example.chirp.post.PostServiceTest
[INFO] Running com.example.chirp.auth.JwtServiceTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.220 s -- in com.example.chirp.auth.JwtServiceTest
[INFO] Running com.example.chirp.ChirpApiIntegrationTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 8.313 s -- in com.example.chirp.ChirpApiIntegrationTest
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESSThat is 4 tests in JwtServiceTest, 4 in PostServiceTest and 3 in the integration test below. A failing test prints the expected and actual values, for example expected: 1 but was: 2, and Maven ends with BUILD FAILURE.
Integration tests with Testcontainers
Unit tests trust that the repositories work. But the repositories are where the risky code is: hand-written SQL, ON CONFLICT DO NOTHING, Flyway migrations, full-text search, Redis lists. An integration test starts the whole application and talks to a real PostgreSQL and Redis.
Testcontainers makes that easy. Before the tests, it starts PostgreSQL 18 and Redis 8.10 in throwaway Docker containers on random ports; after the tests, it deletes them. Every run starts from an empty database, and no test can damage your development data.
@ServiceConnection points Spring at them.- Before any test runs, Testcontainers asks Docker to start a PostgreSQL 18 and a Redis 8.10 container, each on a random free port.
- Spring Boot starts the whole Chirp application.
@ServiceConnectiongives it the containers' addresses, and Flyway runs our real migrations, exactly as in production. - The test sends requests through MockMvc: real security filters, controllers and validation, without opening a network port.
- Our services run their real SQL and Redis commands, including the background fan-out from chapter 6.
- The test checks the status code and the JSON with
jsonPath. When the class finishes, the containers are thrown away.
package com.example.chirp;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.time.Duration;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
import tools.jackson.databind.json.JsonMapper;
/**
* Integration test: the whole application (Spring, Flyway, Hibernate, security) against a REAL
* PostgreSQL and Redis, started in Docker by Testcontainers. Slower than a unit test, but it
* catches what unit tests can't: wrong SQL, missing indexes for a query, security rules, JSON shape.
*/
@SpringBootTest(properties = {
"app.jwt.secret=dGVzdC1zZWNyZXQtdGhhdC1pcy1hdC1sZWFzdC0zMi1ieXRlcy1sb25n",
"app.s3.public-url=http://localhost:9000/chirp-uploads",
"app.s3.access-key=test",
"app.s3.secret-key=test"
})
@AutoConfigureMockMvc
@Testcontainers
class ChirpApiIntegrationTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18-alpine");
@Container
@ServiceConnection(name = "redis")
static GenericContainer<?> redis = new GenericContainer<>("redis:8.10").withExposedPorts(6379);
@Autowired MockMvc mvc;
@Autowired JsonMapper json;
@Test
void followersSeeNewPostsInTheirHomeFeed() throws Exception {
String alice = unique("alice");
String bob = unique("bob");
String aliceToken = register(alice);
String bobToken = register(bob);
mvc.perform(post("/api/users/" + alice + "/follow").header(HttpHeaders.AUTHORIZATION, bearer(bobToken)))
.andExpect(status().isNoContent());
createPost(aliceToken, "First post");
// Bob's first feed read builds his Redis timeline from PostgreSQL.
mvc.perform(get("/api/feed").header(HttpHeaders.AUTHORIZATION, bearer(bobToken)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.items[0].content").value("First post"))
.andExpect(jsonPath("$.items[0].author.username").value(alice));
// A new post is pushed into his timeline in the background (fan-out on write).
createPost(aliceToken, "Second post");
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
mvc.perform(get("/api/feed").header(HttpHeaders.AUTHORIZATION, bearer(bobToken)))
.andExpect(jsonPath("$.items[0].content").value("Second post"))
.andExpect(jsonPath("$.items[1].content").value("First post")));
}
@Test
void requestsWithoutATokenGet401() throws Exception {
mvc.perform(get("/api/feed")).andExpect(status().isUnauthorized());
}
@Test
void invalidRegistrationListsEveryBadField() throws Exception {
mvc.perform(post("/api/auth/register").contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"x\",\"email\":\"nope\",\"password\":\"short\",\"displayName\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.username").exists())
.andExpect(jsonPath("$.errors.email").exists())
.andExpect(jsonPath("$.errors.password").exists())
.andExpect(jsonPath("$.errors.displayName").exists());
}
private String register(String username) throws Exception {
String body = """
{"username":"%s","email":"%s@example.com","password":"correct-horse-battery","displayName":"%s"}
""".formatted(username, username, username);
String response = mvc.perform(post("/api/auth/register").contentType(MediaType.APPLICATION_JSON).content(body))
.andExpect(status().isCreated())
.andReturn().getResponse().getContentAsString();
return json.readTree(response).get("token").asString();
}
private void createPost(String token, String content) throws Exception {
mvc.perform(post("/api/posts").header(HttpHeaders.AUTHORIZATION, bearer(token))
.contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsString(java.util.Map.of("content", content))))
.andExpect(status().isCreated());
}
private static String bearer(String token) {
return "Bearer " + token;
}
private static String unique(String name) {
return name + "_" + UUID.randomUUID().toString().substring(0, 8);
}
}What each piece does
@SpringBootTest(properties = …)starts the full application context. The properties supply the values that production reads from environment variables (a test JWT secret, S3 settings). The S3 presigner only signs URLs offline, so no S3 server is needed here.@AutoConfigureMockMvc(in Spring Boot 4 it lives inorg.springframework.boot.webmvc.test.autoconfigure, from thespring-boot-starter-webmvc-testdependency) creates aMockMvcthat sends requests through the real filter chain.@Testcontainers+@Containerstart and stop the containers. They arestatic, so all tests in the class share one pair of containers. Each test uses fresh random usernames, so tests can't trip over each other.@ServiceConnectionreplaces the old@DynamicPropertySourceboilerplate: Spring reads the container's host, port, user and password directly. For the generic Redis container we give it a name (name = "redis") so Spring knows what kind of service it is.- Awaitility (
await().atMost(…).untilAsserted(…)) handles the one asynchronous thing: the fan-out of a new post runs on a background thread after the commit, so the test retries the check for up to 5 seconds instead of sleeping a fixed time.
Why not an in-memory database such as H2?
H2 is fast and needs no Docker, but it is a different database. Our migrations and queries use PostgreSQL features H2 does not support the same way: BIGSERIAL, the regex CHECK on usernames, ON CONFLICT DO NOTHING, to_tsvector/websearch_to_tsquery and the GIN index. A test that passes on H2 would tell us little about production. Testing against the same database version you deploy is the main reason Testcontainers exists.
Docker must be running for ./mvnw test, because the integration test starts containers. On a laptop, the first run downloads the postgres:18-alpine and redis:8.10 images; later runs reuse them.
End-to-end API tests with a shell script
MockMvc skips the network. The last check of the backend is to call the running server over HTTP, exactly as the React app does. api-test.sh is a plain Bash script that uses curl to send requests and jq to read the JSON. It registers two fresh users and walks through the whole MVP, failing loudly at the first wrong answer.
#!/usr/bin/env bash
# End-to-end API test: registers two users and walks through the main features.
# Needs curl and jq. Usage: ./api-test.sh [base URL, default http://localhost:8080]
set -euo pipefail
BASE="${1:-http://localhost:8080}"
RUN=$(date +%s | tail -c 6) # makes the usernames unique, so you can run it again
PASS=0
# call METHOD PATH [TOKEN] [JSON BODY] -> prints "<status> <body>"
call() {
local method=$1 path=$2 token=${3:-} body=${4:-}
local args=(-s -o /tmp/chirp-body -w '%{http_code}' -X "$method" "$BASE$path")
[[ -n $token ]] && args+=(-H "Authorization: Bearer $token")
[[ -n $body ]] && args+=(-H 'Content-Type: application/json' -d "$body")
local status; status=$(curl "${args[@]}")
echo "$status $(cat /tmp/chirp-body)"
}
# expect NAME EXPECTED_STATUS "<status> <body>"
expect() {
local name=$1 want=$2 got=${3%% *}
if [[ $got != "$want" ]]; then
echo "FAIL $name: expected HTTP $want, got $got"
echo " ${3#* }"
exit 1
fi
PASS=$((PASS + 1))
echo "ok $name ($got)"
}
body() { echo "${1#* }"; }
r=$(call POST /api/auth/register "" "{\"username\":\"alice_$RUN\",\"email\":\"alice_$RUN@example.com\",\"password\":\"correct-horse-1\",\"displayName\":\"Alice\"}")
expect "register alice" 201 "$r"; ALICE=$(body "$r" | jq -r .token)
r=$(call POST /api/auth/register "" "{\"username\":\"bob_$RUN\",\"email\":\"bob_$RUN@example.com\",\"password\":\"correct-horse-2\",\"displayName\":\"Bob\"}")
expect "register bob" 201 "$r"
r=$(call POST /api/auth/register "" "{\"username\":\"bob_$RUN\",\"email\":\"other_$RUN@example.com\",\"password\":\"correct-horse-2\",\"displayName\":\"Bob 2\"}")
expect "same username again is rejected" 409 "$r"
r=$(call POST /api/auth/register "" '{"username":"x","email":"not-an-email","password":"short","displayName":""}')
expect "invalid registration lists the bad fields" 400 "$r"
[[ $(body "$r" | jq '.errors | keys | length') == 4 ]] || { echo "FAIL expected 4 field errors"; exit 1; }
r=$(call POST /api/auth/login "" "{\"username\":\"bob_$RUN\",\"password\":\"wrong-password\"}")
expect "wrong password" 401 "$r"
r=$(call POST /api/auth/login "" "{\"username\":\"BOB_$RUN\",\"password\":\"correct-horse-2\"}")
expect "login (username is case-insensitive)" 200 "$r"; BOB=$(body "$r" | jq -r .token)
expect "feed without a token" 401 "$(call GET /api/feed)"
expect "feed with a tampered token" 401 "$(call GET /api/feed "${BOB%?}x")"
r=$(call POST /api/posts "$ALICE" '{"content":"Hello, Chirp! My first post."}')
expect "alice posts" 201 "$r"; POST_ID=$(body "$r" | jq .id)
long=$(printf 'a%.0s' {1..281})
expect "281 characters is too long" 400 "$(call POST /api/posts "$ALICE" "{\"content\":\"$long\"}")"
r=$(call GET /api/feed "$BOB")
expect "bob's feed before following" 200 "$r"
[[ $(body "$r" | jq '.items | length') == 0 ]] || { echo "FAIL bob's feed should be empty"; exit 1; }
expect "bob follows alice" 204 "$(call POST "/api/users/alice_$RUN/follow" "$BOB")"
expect "following twice is harmless" 204 "$(call POST "/api/users/alice_$RUN/follow" "$BOB")"
r=$(call GET /api/feed "$BOB")
expect "bob's feed after following" 200 "$r"
[[ $(body "$r" | jq '.items[0].id') == "$POST_ID" ]] || { echo "FAIL alice's post should be in bob's feed"; exit 1; }
r=$(call POST "/api/posts/$POST_ID/like" "$BOB")
expect "bob likes the post" 200 "$r"
[[ $(body "$r" | jq .likeCount) == 1 ]] || { echo "FAIL likeCount should be 1"; exit 1; }
r=$(call POST "/api/posts/$POST_ID/like" "$BOB")
[[ $(body "$r" | jq .likeCount) == 1 ]] || { echo "FAIL liking twice must not count twice"; exit 1; }
echo "ok liking twice still counts once"; PASS=$((PASS + 1))
expect "bob comments" 201 "$(call POST "/api/posts/$POST_ID/comments" "$BOB" '{"content":"Welcome!"}')"
r=$(call GET "/api/posts/$POST_ID/comments" "$ALICE")
expect "list comments" 200 "$r"
[[ $(body "$r" | jq .totalItems) == 1 ]] || { echo "FAIL expected 1 comment"; exit 1; }
expect "bob reposts" 200 "$(call POST "/api/posts/$POST_ID/repost" "$BOB")"
r=$(call GET /api/notifications "$ALICE")
expect "alice's notifications" 200 "$r"
[[ $(body "$r" | jq -c '[.[].type]') == '["REPOST","COMMENT","LIKE","FOLLOW"]' ]] || { echo "FAIL notifications: $(body "$r" | jq -c '[.[].type]')"; exit 1; }
r=$(call GET "/api/users/alice_$RUN" "$BOB")
expect "alice's profile" 200 "$r"
[[ $(body "$r" | jq -c '[.followerCount, .postCount, .followedByMe]') == '[1,1,true]' ]] || { echo "FAIL profile counts"; exit 1; }
for i in 1 2 3; do call POST /api/posts "$ALICE" "{\"content\":\"Post number $i\"}" > /dev/null; done
r=$(call GET "/api/feed?size=2" "$BOB")
CURSOR=$(body "$r" | jq .nextCursor)
r=$(call GET "/api/feed?size=2&cursor=$CURSOR" "$BOB")
expect "second page of the feed" 200 "$r"
[[ $(body "$r" | jq '.items[0].id') -lt $CURSOR ]] || { echo "FAIL page 2 must be older than the cursor"; exit 1; }
expect "bob cannot delete alice's post" 403 "$(call DELETE "/api/posts/$POST_ID" "$BOB")"
expect "alice deletes her post" 204 "$(call DELETE "/api/posts/$POST_ID" "$ALICE")"
expect "the post is gone" 404 "$(call GET "/api/posts/$POST_ID" "$ALICE")"
echo "All $PASS checks passed."set -euo pipefailstops the script at the first error, unset variable or failing pipe, so a problem can't scroll past unnoticed.- Unique usernames (
alice_$RUN) mean you can run it again and again against the same database. - It tests the unhappy paths too: duplicate username (409), invalid fields (400 with four errors), wrong password (401), missing and tampered tokens (401), a 281-character post (400), deleting someone else's post (403). Errors are part of the API contract.
With the backend running, run it against port 8080 (or any address):
chmod +x api-test.sh
./api-test.sh http://localhost:8080ok register alice (201)
ok register bob (201)
ok same username again is rejected (409)
ok invalid registration lists the bad fields (400)
ok wrong password (401)
ok login (username is case-insensitive) (200)
ok feed without a token (401)
ok feed with a tampered token (401)
ok alice posts (201)
ok 281 characters is too long (400)
ok bob's feed before following (200)
ok bob follows alice (204)
ok following twice is harmless (204)
ok bob's feed after following (200)
ok bob likes the post (200)
ok liking twice still counts once
ok bob comments (201)
ok list comments (200)
ok bob reposts (200)
ok alice's notifications (200)
ok alice's profile (200)
ok second page of the feed (200)
ok bob cannot delete alice's post (403)
ok alice deletes her post (204)
ok the post is gone (404)
All 25 checks passed.Chapter 6 added a second script, api-test-advanced.sh, for the advanced features: it uploads a file through a presigned URL, checks that S3 rejects an upload with a different Content-Type, and tests search and the profile cache. Its real output:
ok presigned URL for uploads/3/0ab963f1-aaf5-4cd3-91f8-c5fa7f784f3c.png
ok uploaded to S3 (200)
ok S3 rejects a PUT that doesn't match the signature (403)
ok post has the image and anyone can view it
ok cannot attach another user's upload (403)
ok only images can be uploaded (400)
ok full-text search: 'sunsets' finds 'sunset'
ok user search by username prefix
ok profile cache is evicted when the post count changes (1 -> 2)
Advanced checks passed.Alternatives to a shell script
Postman and Bruno let you build request collections with a GUI and add test scripts; both can run collections from the command line in CI. HTTP files (.http, supported by IntelliJ IDEA and VS Code extensions) keep requests as text next to the code. REST Assured writes the same kind of test in Java with JUnit. A shell script is used here because it needs nothing but curl and jq, and every line is visible.
Checking the frontend
The React app has two quick automatic checks. Linting reads the code for likely bugs without running it (oxlint ships with the Vite template and checks, among other things, the rules of hooks). Building compiles every file; a typo in an import fails here instead of in a user's browser.
cd frontend
npm run lint
npm run build> chirp-frontend@0.0.1 lint
> oxlint
> chirp-frontend@0.0.1 build
> vite build
vite v8.3.6 building client environment for production...
✓ 113 modules transformed.
dist/index.html 0.45 kB │ gzip: 0.29 kB
dist/assets/index-BBO8GM1z.css 3.44 kB │ gzip: 1.24 kB
dist/assets/index-DMbaMao0.js 272.07 kB │ gzip: 85.64 kB
✓ built in 165msA clean oxlint run prints nothing after its command line and exits with code 0. The build output above is from the chapter 5 MVP; the chapter 6 version builds the same way, with a slightly larger JavaScript file. The file names contain a content hash (DMbaMao0): change the code and the name changes. We use that for caching in nginx below.
Next steps for frontend tests
This course does not add frontend test code, but these are the usual next tools: Vitest with Testing Library for component tests (render PostCard, click ♡, check the count), and Playwright for browser tests that click through the real app, like the one this course's own test suite uses.
Packaging with Docker
So far we have been running Chirp with tools installed on your computer: Java, Maven, Node. A server would need exactly the same versions. A Docker image packages the program together with everything it needs to run. Any machine with Docker can run it, and it behaves the same everywhere.
Analogy: a shipping container
Before shipping containers, every cargo needed different handling. With standard containers, the crane doesn't care what's inside. A Docker image is a standard box for software: the server only needs to know how to run containers.
Some words you will see: a Dockerfile is the recipe; docker build follows it to make an image; docker run starts a container from the image. Each instruction in a Dockerfile creates a layer, and Docker reuses unchanged layers from earlier builds.
Dockerize the backend
# ---- Stage 1: build the jar with Maven and a full JDK ----
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
# Cached layer: downloads dependencies, and only runs again when pom.xml changes.
RUN mvn -B -q dependency:go-offline
COPY src ./src
# Tests run in CI before the image is built, so skip them here.
RUN mvn -B -q package -DskipTests
# ---- Stage 2: a small image with only the Java runtime and the jar ----
FROM eclipse-temurin:21-jre
WORKDIR /app
RUN useradd --system --no-create-home chirp
COPY --from=build /app/target/chirp-0.0.1-SNAPSHOT.jar app.jar
# Don't run as root.
USER chirp
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]- Two stages. The first stage (
AS build) has Maven and a full JDK, which we need to compile. The second stage starts again from a small image with only the Java runtime and copies in just the finished jar. Compilers and Maven's download cache stay behind, so the final image is smaller and has less software that could have security holes. This is a multi-stage build. - Copy
pom.xmlfirst, source second.dependency:go-offlinedownloads the libraries in its own layer. As long aspom.xmldoesn't change, Docker reuses that layer, and rebuilding after a code change skips the downloads. - Not root.
useraddcreates a system user andUSER chirpruns the app as that user. If someone ever exploits a bug in the app, they don't get root inside the container. -XX:MaxRAMPercentage=75lets Java size its heap from the container's memory limit (75% of it), leaving room for the rest of the process.-DskipTestsbecause tests run in CI before the image is built (see the pipeline), and the integration test would need Docker inside Docker.
target
.idea
*.iml.dockerignore keeps local build output out of the build context (what Docker copies before building), so a stale target/ folder never sneaks into the image.
A real bug: comments at the end of a line
The first version of this Dockerfile had USER chirp # don't run as root on one line. Unlike most languages, a Dockerfile only treats # as a comment at the start of a line, so Docker read the comment as part of the user name and the build failed:
target backend: failed to solve: failed to process "chirp # don't run as root": unexpected end of statement while looking for matching single-quoteThe fix is in the file above: every comment sits on its own line.
Dockerize the frontend
The React app is just static files after npm run build. We build them with Node in the first stage, then serve them with nginx, a small, fast web server, in the second. Node is not in the final image at all.
# ---- Stage 1: build the static files with Node ----
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
# npm ci installs the exact versions from package-lock.json.
RUN npm ci
COPY . .
# Writes the optimised site to dist/
RUN npm run build
# ---- Stage 2: serve them with nginx ----
FROM nginx:1.30-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/htmlnode_modules
distnpm ci (not npm install) installs exactly the versions in package-lock.json and fails if the two files disagree. That makes builds repeatable. Ignoring node_modules matters: it is large, and a copy built on macOS or Windows can contain the wrong native binaries for the Linux image.
nginx: one address for the whole app
In development, Vite's proxy sent /api and /ws to Spring Boot so the browser saw one origin (chapter 5). In production nginx does the same job, and also serves the React files:
server {
listen 80;
root /usr/share/nginx/html;
# API calls go to Spring Boot ("backend" is the service name in compose.prod.yaml).
# $http_host keeps the port (localhost:8088); $host would drop it.
location /api/ {
proxy_pass http://backend:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 1m; # images go to S3, so API bodies stay small
}
# WebSocket: HTTP/1.1 plus the Upgrade headers, and a long timeout for idle connections.
# Spring only accepts same-origin WebSockets: the Host it sees must match the page's Origin,
# port included, so pass $http_host here too.
location /ws {
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_read_timeout 1h;
}
# Built files have a content hash in their name (index-BBO8GM1z.js), so they can be cached forever.
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
# React Router handles /u/alice and /posts/42 in the browser: serve index.html for any other path.
location / {
try_files $uri /index.html;
add_header Cache-Control "no-cache";
}
}location /api/forwards API calls tohttp://backend:8080.backendis the service name in Compose; Docker's internal DNS turns it into the container's address. TheX-Forwarded-*headers tell Spring the original client address and scheme.location /wsforwards WebSockets. A WebSocket starts as an HTTP request that asks to upgrade the connection, so nginx must use HTTP/1.1 and pass theUpgradeandConnectionheaders.proxy_read_timeout 1hstops nginx closing quiet connections after its default 60 seconds.location /assets/lets browsers cache the hashed files for a year (immutable): a new build has new file names, so a stale cache is never a problem.try_files $uri /index.htmlis the SPA fallback./u/aliceis not a file on disk; it is a React Router route. Without this line, refreshing a profile page would show nginx's 404.index.htmlitself getsno-cache, so users pick up new deployments immediately.
A real bug: $host versus $http_host
The first version used proxy_set_header Host $host. Everything worked except live notifications. The browser console showed:
WebSocket connection to 'ws://localhost:8088/ws?token=eyJ…' failed: Error during WebSocket handshake: Unexpected response code: 403Spring only accepts same-origin WebSockets: it compares the page's Origin (http://localhost:8088) with the Host header it receives. nginx's $host drops the port, so Spring saw localhost, decided the origins differ, and refused. $http_host passes the header exactly as the browser sent it, port included. On a real domain on port 443 both variables are the same, which is why this bug often only appears on a laptop.
The production request path
Here is how a request travels once everything runs in containers. Press Play:
- The browser asks for
/u/alice. nginx finds no such file and returnsindex.html(the SPA fallback), then the hashed JavaScript from/assets/. - React Router shows the profile page, which calls the API. The request goes to the same origin, so there is no CORS.
- nginx forwards everything under
/api/to the backend container by its Compose service name. - Spring checks the JWT, reads the profile card from Redis (or PostgreSQL on a miss) and the "followed by me" flag from PostgreSQL.
- The JSON goes back through nginx to the browser.
- Image uploads skip nginx and the backend entirely: the browser sends the file straight to S3 with a presigned URL (chapter 6).
Environment variables and secrets
A secret is any value that gives access: the JWT signing key, database passwords, cloud credentials. If a secret leaks, someone can forge tokens or read your data. The rule is simple: secrets never go in code, in Git, or in a Docker image. They are given to the program from outside, as environment variables, when it starts.
Chirp was built this way from chapter 4. application.yml contains placeholders, not values:
datasource:
url: ${DB_URL}
username: ${DB_USER}
password: ${DB_PASSWORD}
jpa:
open-in-view: false # no lazy loading after the service method returns
hibernate:
ddl-auto: validate # Flyway owns the schema; Hibernate only checks it matches the entities
mvc:
problemdetails:
enabled: true # errors come back as RFC 9457 "problem detail" JSON
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
threads:
virtual:
enabled: true # Java 21 virtual threads for requests and @Async work
app:
jwt:
secret: ${JWT_SECRET} # base64 of at least 32 random bytes; never commit a real one
ttl: 24h${DB_URL} means "read the DB_URL environment variable". There is no default after a colon, so a missing value is noticed at start-up, not hours later. (Chapter 4 showed the error a missing DB_URL produces: 'url' must start with "jdbc".) The development values live in application-dev.yml, which is only used with the dev profile and contains nothing that works in production.
The .env file
Docker Compose reads a file called .env next to the compose file and substitutes its values. We commit an example with fake values, and Git ignores the real one:
# Copy to .env and change every value. Never commit .env (it is in .gitignore).
# Make a JWT secret with: openssl rand -base64 32
JWT_SECRET=change-me-run-openssl-rand-base64-32
DB_PASSWORD=change-me
S3_SECRET_KEY=change-me-too
# Where browsers reach the S3 server. On a real server use its public address (or real S3/CloudFront).
S3_PUBLIC_ENDPOINT=http://localhost:9000.envcp .env.example .env
# make a strong random JWT secret (32 random bytes, base64) and paste it into .env
openssl rand -base64 32openssl rand -base64 32 prints 44 random characters, different every time. 32 bytes is 256 bits, the minimum jjwt accepts for HS256 (shorter keys fail at start-up with WeakKeyException, as chapter 4 showed).
Baked into the image
An ENV JWT_SECRET=… line in a Dockerfile is stored in the image layers. Anyone who can pull the image can read it with docker history or docker inspect, forever.
Given at run time
Compose passes JWT_SECRET from .env when the container starts. The image is the same for every environment; only the values differ.
In the cloud: secret stores and roles
On AWS, keep secrets in AWS Secrets Manager or Systems Manager Parameter Store (SecureString) and let the platform inject them as environment variables; ECS task definitions support this directly. For AWS itself, don't use access keys at all: give the EC2 instance or ECS task an IAM role that may only write to the uploads bucket. Chirp's S3Config already falls back to the SDK's default credential chain when no access key is set, which picks up that role automatically.
Run the production stack on your computer
compose.prod.yaml describes all six containers. Running it locally is the best rehearsal for a real deployment: if it works here, a server only needs Docker and this file.
# The whole application in containers: browser -> nginx (React + proxy) -> Spring Boot -> PostgreSQL / Redis / S3.
# cp .env.example .env (then put real secrets in .env)
# docker compose -f compose.prod.yaml up -d --build
# Open http://localhost:8088
services:
postgres:
image: postgres:18-alpine
restart: unless-stopped
environment:
POSTGRES_DB: chirp
POSTGRES_USER: chirp
POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U chirp -d chirp"]
interval: 5s
timeout: 3s
retries: 10
redis:
image: redis:8.10
restart: unless-stopped
s3:
image: rustfs/rustfs:1.0.4
restart: unless-stopped
environment:
RUSTFS_ACCESS_KEY: chirp
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:?set S3_SECRET_KEY in .env}
ports:
- "9000:9000" # browsers upload to and read images from here
volumes:
- s3data:/data
s3-init:
image: amazon/aws-cli:2.39.4
depends_on:
- s3
environment:
AWS_ACCESS_KEY_ID: chirp
AWS_SECRET_ACCESS_KEY: ${S3_SECRET_KEY}
AWS_DEFAULT_REGION: us-east-1
volumes:
- ./s3:/s3:ro
entrypoint: ["/bin/sh", "-c"]
command:
- |
until aws --endpoint-url http://s3:9000 s3api list-buckets > /dev/null 2>&1; do sleep 1; done
aws --endpoint-url http://s3:9000 s3api create-bucket --bucket chirp-uploads 2> /dev/null || true
aws --endpoint-url http://s3:9000 s3api put-bucket-policy --bucket chirp-uploads --policy file:///s3/bucket-policy.json
aws --endpoint-url http://s3:9000 s3api put-bucket-cors --bucket chirp-uploads --cors-configuration file:///s3/cors.json
backend:
build: ./backend
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
environment:
DB_URL: jdbc:postgresql://postgres:5432/chirp
DB_USER: chirp
DB_PASSWORD: ${DB_PASSWORD}
JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET in .env}
REDIS_HOST: redis
S3_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:9000}
S3_PUBLIC_URL: ${S3_PUBLIC_ENDPOINT:-http://localhost:9000}/chirp-uploads
S3_ACCESS_KEY: chirp
S3_SECRET_KEY: ${S3_SECRET_KEY}
# No "ports": only nginx can reach the backend.
frontend:
build: ./frontend
restart: unless-stopped
depends_on:
- backend
ports:
- "8088:80"
volumes:
pgdata:
s3data:Service by service
| Service | What to notice |
|---|---|
postgres | A named volume (pgdata) keeps the data when the container is replaced. The healthcheck runs pg_isready every 5 seconds. ${DB_PASSWORD:?…} makes Compose refuse to start if the variable is missing. |
redis | No volume: Redis only holds caches and timelines that can be rebuilt from PostgreSQL. |
s3 + s3-init | The S3-compatible server from chapter 6, and a one-shot container that creates the bucket, its read policy and CORS rules, then exits. On AWS you would use real S3 and drop both. |
backend | build: ./backend builds the Dockerfile. depends_on … condition: service_healthy waits for PostgreSQL to accept connections, not just to start, so Flyway doesn't fail on the first boot. No ports: nothing outside Docker can reach it directly. |
frontend | nginx, the only web entry point, published on port 8088. |
restart: unless-stopped brings containers back after a crash or a server reboot.
docker compose -f compose.prod.yaml up -d --build
docker compose -f compose.prod.yaml ps
# a protected endpoint without a token must answer 401 through nginx
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8088/api/auth/me
# a React route must get index.html (the SPA fallback)
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://localhost:8088/u/alice
# the end-to-end tests, through nginx this time
./api-test.sh http://localhost:8088401
200 text/html
…
All 25 checks passed.Open http://localhost:8088 and use the app. When you're done, docker compose -f compose.prod.yaml down stops everything; add -v only if you also want to delete the data volumes.
Deploy it
There are many ways to host an app. Here are two that cover most needs: the simplest possible one, and the one most companies grow into. Both run the same images.
Option A: one server with Docker Compose
The cheapest and simplest setup: one virtual server (an Amazon EC2 instance, Amazon Lightsail, or any VPS) running exactly the stack you just ran locally. Fine for a personal project or a small community.
- Create the server with a recent Ubuntu or Debian, 2 GB of memory or more, and a firewall that only allows SSH (22), HTTP (80) and HTTPS (443). Point your domain's DNS at its address.
- Install Docker (Docker Engine with the Compose plugin) following the official instructions for your Linux distribution.
- Copy the project (
git clone, orscp) and create.envwith new secrets. SetS3_PUBLIC_ENDPOINTto the address browsers will use, and add your domain tos3/cors.json. - Start it:
docker compose -f compose.prod.yaml up -d --build. Remove the published ports you don't want public: in production, only the reverse proxy should listen on the internet. - Add HTTPS with a reverse proxy such as Caddy, which obtains and renews Let's Encrypt certificates automatically. Its whole configuration is one site block for your domain containing a single
reverse_proxy localhost:8088line. Browsers block many features on plain HTTP, and tokens must never travel unencrypted. - Back up the database on a schedule, for example a nightly
docker compose exec postgres pg_dump -U chirp chirpcopied to S3, and practise restoring it once. A backup you have never restored is a hope, not a backup.
The weak spot is that one machine is a single point of failure, and you are responsible for its updates. That is the trade-off for simplicity.
Option B: managed AWS services
Each piece moves to a service that AWS runs for you, with backups, patching and failover built in. More moving parts and a higher bill, but much less to look after as usage grows.
- CloudFront
- Amazon's CDN: serves files from locations near each user, with HTTPS. This very website, DevToolbox, is a static site served from S3 through CloudFront in exactly this way.
- S3 bucket for the React build
- Upload the
dist/folder. Configure CloudFront to answer unknown paths with/index.html, the same SPA fallback nginx gave us. The bucket stays private; only CloudFront may read it. - S3 bucket for uploads
- The presigned uploads from chapter 6 go here. Serve them through CloudFront too, and set
S3_PUBLIC_URLto the CloudFront address. - Application Load Balancer
- Spreads API and WebSocket traffic over several backend containers and terminates HTTPS with a free certificate from AWS Certificate Manager (ACM). Its health checks use
/actuator/health. - ECS on Fargate
- Runs our backend image without managing servers. Secrets come from Secrets Manager or Parameter Store; S3 access comes from the task's IAM role. (EC2 instances behind the same load balancer also work.)
- Amazon RDS for PostgreSQL
- Managed PostgreSQL with automated backups, point-in-time restore and an optional standby in a second availability zone. Flyway migrates it on start-up exactly as before.
- Amazon ElastiCache
- Managed Valkey or Redis for the profile cache and timelines. With more than one backend container, live notifications also need Redis pub/sub (chapter 7).
Because the React app talks to /api on its own origin, the simplest option-B setup puts both behind one domain: CloudFront can forward /api/* and /ws to the load balancer and everything else to the S3 bucket. Otherwise you need CORS on the backend, which chapter 2 explained.
Continuous integration and delivery
Running tests by hand is easy to forget. A CI/CD pipeline runs them on a build server for every push, and only a commit that passes everything becomes a new image that gets deployed. Step through it:
- You push a commit. The CI service (GitHub Actions, GitLab CI, Jenkins…) starts a fresh machine and checks out the code.
- It compiles the backend and builds and lints the frontend. A syntax error stops everything here.
- Unit tests run in seconds; then the integration test starts PostgreSQL and Redis containers on the build machine.
- Only now are the two images built, tagged with the commit id (so you always know what is running), and pushed to a registry such as Amazon ECR.
- The new images are deployed, and a short smoke test (for example
api-test.sh) runs against the live system. If it fails, roll back to the previous tag.
Show a GitHub Actions workflow for the test stages
Simplified example — not part of the tested project
This workflow runs the same commands this chapter ran by hand. GitHub's hosted Ubuntu runners include Docker, which the Testcontainers test needs. Adapt the image and deploy stages to your registry and hosting.
name: ci
on: [push, pull_request]
jobs:
backend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- run: ./mvnw -B test
frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- run: npm run lint
- run: npm run buildProduction checklist
Before real people trust Chirp with an account, go through this list. Tick items as you do them; your ticks are saved in this browser only.
Common mistakes
Testing only the happy path
Tests that only register, post and like successfully miss the bugs attackers look for: deleting someone else's post, liking twice, using a forged token.
Fix: for each rule, write the test that tries to break it. api-test.sh checks eight error responses for that reason.
Tests that depend on each other or on fixed data
A test that registers alice fails the second time it runs ("username taken"), or fails only when tests run in a different order.
Fix: every test creates its own data with unique names (UUID, a timestamp), as Chirp's tests do.
Thread.sleep to wait for background work
Sleep too little and the test fails randomly on a slow build machine; sleep too much and the suite gets slow.
Fix: poll with a timeout, using Awaitility's await().atMost(…).untilAsserted(…).
Committing .env or putting secrets in the Dockerfile
Git history and image layers keep secrets forever, even after you delete the line.
Fix: .env in .gitignore, values only at run time. If a secret ever leaks, rotate it: generate a new one and treat the old one as public.
Comments at the end of Dockerfile lines
USER chirp # comment fails with "unexpected end of statement while looking for matching single-quote".
Fix: put comments on their own lines.
Refreshing /u/alice gives 404 in production
The web server looks for a file called u/alice and doesn't find one.
Fix: an SPA fallback: try_files $uri /index.html in nginx, or a custom error response to /index.html in CloudFront.
WebSockets get 403 or close after a minute behind a proxy
Missing Upgrade/Connection headers, a Host header without the port ($host), or the proxy's default 60-second read timeout.
Fix: the location /ws block in this chapter's nginx.conf.
docker compose down -v on a server
-v deletes the named volumes, which means the whole database.
Fix: use plain down to stop, and keep backups anyway.
Key takeaways
- Many fast unit tests, fewer integration tests, a few end-to-end tests: each level catches bugs the others miss.
- Mockito isolates one class; Testcontainers tests the real SQL against the same PostgreSQL version you deploy.
- Test the error cases: they are part of your API, and they are where the security bugs hide.
- Multi-stage Dockerfiles produce small images without build tools; run as a non-root user.
- nginx serves the React build, proxies
/apiand/ws, and falls back toindex.htmlfor client-side routes. - Secrets come from the environment at run time: never from Git or image layers.
- Start with one server and Compose; move pieces to managed services when looking after them yourself costs more than paying for them.
Check your understanding
Which test would catch a typo in the SQL of findFeedIds?
- A unit test of
FeedServicewith a mockedPostRepository - An integration test against a real PostgreSQL
- Running
npm run lint
Why does the backend Dockerfile copy pom.xml and download dependencies before copying src?
- Maven needs the files in that order to compile
- It makes the final image smaller
- Docker reuses the dependency layer when only the source code changed, so rebuilds are faster
pom.xml, so keeping the slow download in its own earlier layer means most rebuilds skip it.A user refreshes the page at https://chirp.example.com/u/alice and gets "404 Not Found" from the web server. What is missing?
- A fallback that serves
index.htmlfor unknown paths - A route for
/u/:usernamein the Spring Boot backend - CORS headers
/u/alice is handled by React Router in the browser. The server has to return index.html for it (nginx try_files $uri /index.html), and React does the rest.Where should the production JWT_SECRET live?
- In
application.yml, so it is versioned with the code - In the environment at run time, e.g. a
.envfile on the server or a secrets manager - In the Dockerfile as an
ENVline
Exercise: test a rule yourself
Add a unit test to PostServiceTest that proves unliking a post you never liked leaves the count alone: likes.remove returns false, and addToLikeCount must never be called. Then run ./mvnw test -Dtest=PostServiceTest and check that Maven now reports 5 tests in that class.
Show a sample answer
Add this method inside the class; it uses only imports the file already has:
@Test
void unlikingAPostYouNeverLikedChangesNothing() {
when(posts.findById(10L)).thenReturn(Optional.of(alicesPost));
when(likes.remove(2L, 10L)).thenReturn(false); // there was no like to remove
when(posts.findLikeCount(10L)).thenReturn(0);
LikeResponse result = postService.unlike(bob, 10L);
assertThat(result).isEqualTo(new LikeResponse(false, 0));
verify(posts, never()).addToLikeCount(anyLong(), anyInt());
}Try breaking PostService.unlike on purpose (remove the if) and watch the test fail. A test you have never seen fail might not be testing anything.
You built Twitter from scratch
Look back at what is now in your chirp folder:
- A data modelSeven PostgreSQL tables with keys, constraints, indexes and versioned migrations.
- A secure REST APISpring Boot with BCrypt passwords, JWT authentication and ownership checks.
- A React appFeed, composer, profiles, replies, follows and optimistic likes.
- Real-time and mediaRedis timelines and cache, WebSocket notifications, S3 uploads, full-text search.
- Tests at every levelUnit, integration with real databases, end-to-end API checks.
- A deployable systemDocker images, nginx, Compose, secrets handled properly.
Most importantly, you know why each piece exists, which is what lets you design the next system yourself.
Where to go next
- Add features: bookmarks (the chapter 1 exercise), direct messages (a new table and WebSocket messages between two users), hashtags and trends (extract tags when posting, count them per hour in Redis).
- Harden it: rate limiting on login, refresh tokens with short-lived access tokens, account deletion.
- Observe it: metrics with Micrometer and Prometheus (add the
micrometer-registry-prometheusdependency and expose Actuator'sprometheusendpoint), dashboards, and tracing with OpenTelemetry. - Scale it: revisit chapter 7 and try one change, such as running two backend containers behind nginx and delivering notifications through Redis pub/sub.
- Keep learning: the system design roadmap, the Docker roadmap and the AWS roadmap on this site go deeper on each area.
Want to go through it again, or share it with someone? The course starts at chapter 1: what we are building.
Finished this chapter? Tick it off. Progress is saved in this browser only.