What you will learn
- Create a Spring Boot 4 project and understand every file in it
- Connect to PostgreSQL with Flyway migrations and JPA entities
- Register and log in users with BCrypt and JSON Web Tokens
- Build the REST API for posts, follows, likes, reposts, comments and notifications
- Build the home feed with cursor pagination, and turn errors into clean JSON
Why it matters
The backend is where the rules live. The browser can be changed by anyone with developer tools, so every promise Chirp makes ("only you can delete your posts", "a like counts once", "280 characters") must be enforced here. By the end of this chapter you will have a complete, tested MVP API that the React app in chapter 5 talks to.
Every file, tested
This chapter shows all 48 files of the MVP backend, in the order you would write them. The same files were compiled, started against PostgreSQL 18 and checked with 25 end-to-end API tests before publishing. If you copy them into the same folders, your project will match ours exactly. Long files are folded: press Show all lines to expand them, and Copy to copy the whole file.
Create the Spring Boot project
Spring Boot is a framework that sets up the boring parts of a Java server for us: a web server (Tomcat) inside our program, JSON conversion, database connections and security. We write the parts that are specific to Chirp, and Spring Boot provides everything else with sensible defaults.
The easiest way to start is start.spring.io, the official project generator. Choose:
| Setting | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 4.1.2 |
| Group / Artifact | com.example / chirp (package com.example.chirp) |
| Packaging / Java | Jar / 21 |
| Dependencies | Spring Web, Spring Data JPA, Spring Security, Validation, Flyway Migration, PostgreSQL Driver, Spring Boot Actuator, Testcontainers |
Press Generate, unzip the download into your chirp folder and rename it to backend. The zip includes mvnw, the Maven wrapper: a small script that downloads the right Maven version the first time you run it, so you don't have to install Maven yourself. On Windows use mvnw.cmd instead of ./mvnw.
pom.xml: the shopping list
Maven reads pom.xml to find out which libraries (dependencies) to download and how to build the jar. The spring-boot-starter-parent at the top picks compatible versions for every Spring library, which is why most dependencies have no version number. The generator gives you almost all of this file; the only part you add by hand is jjwt, the library we use to create and check JSON Web Tokens.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>chirp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>chirp</name>
<properties>
<java.version>21</java.version>
<jjwt.version>0.13.0</jjwt.version>
</properties>
<dependencies>
<!-- REST controllers, JSON and the embedded Tomcat server -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<!-- JPA entities and repositories (Hibernate) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Password hashing, the filter chain, @AuthenticationPrincipal -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- @NotBlank, @Size, @Email on request bodies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Runs the SQL files in db/migration when the app starts -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-flyway</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
<!-- /actuator/health for Docker and load balancers -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- JSON Web Tokens -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Tests (chapter 8) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-postgresql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>What each dependency gives us
spring-boot-starter-webmvc: controllers (@RestController), JSON with Jackson 3, and the embedded Tomcat web server. In Spring Boot 4 this is the new name of the old "web" starter.spring-boot-starter-data-jpa: Hibernate 7 and Spring Data repositories, so we can work with Java objects instead of writing every SQL statement. It also gives usJdbcClientfor the places where plain SQL is clearer.spring-boot-starter-security: BCrypt password hashing and the security filter chain that checks every request.spring-boot-starter-validation: annotations such as@NotBlankand@Sizethat check request bodies before our code runs.spring-boot-starter-flyway+flyway-database-postgresql: run the SQL files indb/migrationat start-up, exactly once each.spring-boot-starter-actuator:/actuator/health, which Docker and load balancers use to ask "are you alive?".postgresql(runtime): the JDBC driver that speaks PostgreSQL's network protocol.jjwt-api,jjwt-impl,jjwt-jackson: create and verify JWTs. Only the API is needed to compile; the other two are used at run time.- The
…-teststarters, Testcontainers: used in chapter 8. Leaving them here now means the file doesn't change later.
Organise by feature, not by layer
We put the classes for each feature in one package (post, user, comment…) instead of one package per layer (controllers, services…). When you work on likes, everything about likes is in one folder, and a feature can later be moved into its own service (chapter 7) without untangling it from the rest.
backend/
├── pom.xml
└── src/main/
├── java/com/example/chirp/
│ ├── ChirpApplication.java starts everything
│ ├── config/SecurityConfig.java which requests need a token
│ ├── common/ApiExceptionHandler errors → JSON
│ ├── auth/ register, login, JWT
│ ├── user/ users, profiles, follows
│ ├── post/ posts, likes, reposts
│ ├── comment/ replies
│ ├── feed/ the home feed
│ └── notification/
└── resources/
├── application.yml settings for every environment
├── application-dev.yml settings for your machine only
└── db/migration/V1__create_schema.sqlThe main class
Every Spring Boot app starts from one class with a main method. @SpringBootApplication tells Spring to scan this package and everything below it for our classes, and to switch on auto-configuration: Spring looks at what is on the classpath ("PostgreSQL driver? Then make a connection pool.") and configures it.
package com.example.chirp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration;
// We check passwords ourselves (AuthService), so turn off Spring Boot's default
// in-memory user and its "Using generated security password" log line.
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
@ConfigurationPropertiesScan // finds @ConfigurationProperties records such as JwtProperties
public class ChirpApplication {
public static void main(String[] args) {
SpringApplication.run(ChirpApplication.class, args);
}
}Why the exclude? When Spring Security is present and you haven't told it how to find users, Spring Boot creates one in-memory user with a random password and prints it at start-up. We check passwords ourselves in AuthService, so that user would only be confusing. Without the exclude, you would see this real warning on every start:
WARN 1 --- [chirp] [ main] .s.a.UserDetailsServiceAutoConfiguration :
Using generated security password: fba44f3b-2ece-46ca-8f67-de962c49b6f2
This generated password is for development use only. Your security configuration must be updated before running your application in production.Connect to PostgreSQL
We need a running PostgreSQL. Instead of installing it, we run it in Docker. Create compose.yaml in the chirp folder (next to backend, not inside it):
# Development services. Start them with: docker compose up -d
services:
postgres:
image: postgres:18-alpine
environment:
POSTGRES_DB: chirp
POSTGRES_USER: chirp
POSTGRES_PASSWORD: chirp
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql
volumes:
pgdata:The volumes line keeps the data in a Docker volume, so it survives restarts. Start it:
docker compose up -dSettings: application.yml
Spring Boot reads settings from src/main/resources/application.yml. The ${DB_URL} syntax means "take this from an environment variable", so the same file works on your laptop and in production without containing any passwords.
spring:
application:
name: chirp
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
app:
jwt:
secret: ${JWT_SECRET} # base64 of at least 32 random bytes; never commit a real one
ttl: 24h
management:
endpoints:
web:
exposure:
include: healthddl-auto: validate: Hibernate checks at start-up that every entity matches a real table and column, but never changes the database. Changes happen only through Flyway migrations, so production databases are never altered by accident.open-in-view: false: database work must be finished when the service method returns. This avoids slow, hidden queries while JSON is being written, at the cost of an error if we forget to load something (see mistakes).problemdetails.enabled: errors come back in the standard problem details JSON format (RFC 9457) instead of an HTML error page.
For your own machine, a second file adds the missing values. Spring Boot loads application-dev.yml on top of application.yml when the profile named dev is active:
# Settings for your own machine only. Start the app with the "dev" profile to use them:
# ./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
spring:
datasource:
url: jdbc:postgresql://localhost:5432/chirp
username: chirp
password: chirp
jpa:
show-sql: true # print every SQL statement Hibernate runs (handy while learning)
app:
jwt:
# A throwaway development key. Production reads JWT_SECRET from the environment instead.
secret: ZGV2LW9ubHktc2VjcmV0LWtleS1mb3ItY2hpcnAtZG8tbm90LXVzZS1pbi1wcm9kThis secret is for development only
The JWT key in application-dev.yml is public: it's on this page. That is fine for a laptop, never for a real server. In production the dev profile is not active, so the app must get JWT_SECRET, DB_URL and the rest from environment variables, and it refuses to start without them. Chapter 8 shows how to make a real secret.
The schema: V1__create_schema.sql
This is the SQL we designed in chapter 3. Put it in src/main/resources/db/migration/. Flyway runs every file in that folder once, in version order, and records it in a table called flyway_schema_history.
-- V1: the whole MVP schema. Flyway runs this file once, in order, and records it in flyway_schema_history.
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE,
email VARCHAR(254) NOT NULL UNIQUE,
password_hash VARCHAR(100) NOT NULL,
display_name VARCHAR(50) NOT NULL,
bio VARCHAR(160) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
-- usernames are stored in lower case: letters, digits and underscores only
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,30}$')
);
CREATE TABLE posts (
id BIGSERIAL PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
content VARCHAR(280) NOT NULL,
image_url VARCHAR(500),
like_count INTEGER NOT NULL DEFAULT 0,
comment_count INTEGER NOT NULL DEFAULT 0,
repost_count INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- "Newest posts by this author" (profile pages and the home feed).
CREATE INDEX posts_author_id_id_idx ON posts (author_id, id DESC);
CREATE TABLE follows (
follower_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
followee_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (follower_id, followee_id),
CONSTRAINT follows_not_self CHECK (follower_id <> followee_id)
);
-- The primary key answers "who does X follow?"; this index answers "who follows X?".
CREATE INDEX follows_followee_id_idx ON follows (followee_id);
CREATE TABLE likes (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
post_id BIGINT NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, post_id)
);
CREATE INDEX likes_post_id_idx ON likes (post_id);
CREATE TABLE reposts (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
post_id BIGINT NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, post_id)
);
CREATE INDEX reposts_post_id_idx ON reposts (post_id);
CREATE TABLE comments (
id BIGSERIAL PRIMARY KEY,
post_id BIGINT NOT NULL REFERENCES posts (id) ON DELETE CASCADE,
author_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
content VARCHAR(280) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX comments_post_id_id_idx ON comments (post_id, id);
CREATE TABLE notifications (
id BIGSERIAL PRIMARY KEY,
recipient_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
actor_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
type VARCHAR(20) NOT NULL,
post_id BIGINT REFERENCES posts (id) ON DELETE CASCADE,
is_read BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT notifications_type_check CHECK (type IN ('LIKE', 'COMMENT', 'FOLLOW', 'REPOST'))
);
CREATE INDEX notifications_recipient_id_id_idx ON notifications (recipient_id, id DESC);First run
With only these files, the app already starts. Run it with the dev profile:
cd backend
./mvnw spring-boot:run -Dspring-boot.run.profiles=devThe first run downloads dependencies, which takes a few minutes. Then look for these lines (shortened; your times will differ):
INFO … ChirpApplication : The following 1 profile is active: "dev"
INFO … FlywayExecutor : Database: jdbc:postgresql://localhost:5432/chirp (PostgreSQL 18.6)
INFO … DbValidate : Successfully validated 1 migration (execution time 00:00.016s)
INFO … DbMigrate : Current version of schema "public": << Empty Schema >>
INFO … DbMigrate : Migrating schema "public" to version "1 - create schema"
INFO … DbMigrate : Successfully applied 1 migration to schema "public", now at version v1 (execution time 00:00.036s)
INFO … TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
INFO … ChirpApplication : Started ChirpApplication in 4.876 seconds (process running for 5.23)Check that it's alive from a second terminal:
curl http://localhost:8080/actuator/health{"groups":["liveness","readiness"],"status":"UP"}If you forget the dev profile, nothing fills in ${DB_URL} and start-up fails with this real error (shortened):
Error creating bean with name 'dataSource' … Failed to instantiate [com.zaxxer.hikari.HikariDataSource]:
Factory method 'dataSource' threw exception with message: 'url' must start with "jdbc"How a request moves through the backend
Before writing features, it helps to know where each piece of code goes. Every request passes through the same layers, each with one job:
- The browser sends
POST /api/postswith a JSON body and anAuthorization: Bearer …header. - Spring Security's filters run first.
JwtAuthFilterchecks the token's signature and records who is calling. No valid token? The request stops here with 401. - The controller turns HTTP into Java: JSON becomes a
CreatePostRequestobject,@Validchecks it (not blank, at most 280 characters), and it calls the service. - The service applies the business rules and decides what to save. It's the only layer that knows what "posting" means.
- The repository turns Java into SQL and sends it to PostgreSQL.
- PostgreSQL stores the row and returns the new id.
- The service returns a
PostResponse; the controller turns it into JSON with status201 Created.
Analogy: a restaurant
The security filter is the host checking your reservation. The controller is the waiter who takes your order and brings food back, but never cooks. The service is the chef who decides how dishes are made. The repository is the pantry assistant who fetches ingredients. Each person can be replaced without retraining the others.
Beans and dependency injection, in one minute
Classes marked @Service, @Repository, @RestController, @Component or @Configuration are created by Spring at start-up, once each. These objects are called beans. When a bean needs another one, it simply asks for it in its constructor, and Spring passes it in. That is dependency injection: PostService never writes new PostRepository(); it receives the one Spring made. Tests can then pass in fakes instead (chapter 8).
Entities and DTOs: two kinds of object
An entity (User, Post) mirrors a table row and is managed by Hibernate. A DTO (data transfer object, like PostResponse) is the shape of the JSON our API promises to send. We always convert entities to DTOs before answering. If we returned the User entity directly, the JSON would include passwordHash and email, and every database change would silently change our public API. Java records (record PostResponse(…)) are perfect for DTOs: one line declares the fields, constructor, getters, equals and toString.
Users and registration
The User entity
@Entity tells Hibernate "objects of this class are rows in a table". @Table names the table, @Id marks the primary key, and @GeneratedValue(strategy = IDENTITY) lets PostgreSQL's BIGSERIAL choose the id. @Column maps Java names (passwordHash) to SQL names (password_hash). The empty protected constructor is required by JPA; we use the other one.
package com.example.chirp.user;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // PostgreSQL's BIGSERIAL picks the id
private Long id;
@Column(nullable = false, unique = true, length = 30)
private String username;
@Column(nullable = false, unique = true, length = 254)
private String email;
@Column(name = "password_hash", nullable = false, length = 100)
private String passwordHash;
@Column(name = "display_name", nullable = false, length = 50)
private String displayName;
@Column(nullable = false, length = 160)
private String bio = "";
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt = Instant.now();
protected User() {
// for JPA
}
public User(String username, String email, String passwordHash, String displayName) {
this.username = username;
this.email = email;
this.passwordHash = passwordHash;
this.displayName = displayName;
}
public Long getId() { return id; }
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getPasswordHash() { return passwordHash; }
public String getDisplayName() { return displayName; }
public String getBio() { return bio; }
public Instant getCreatedAt() { return createdAt; }
}The UserRepository: queries from method names
A repository is an interface; Spring Data writes the class for us. Extending JpaRepository<User, Long> gives save, findById, delete and more. Methods named findByUsername or existsByEmail are turned into SQL from their names. When the name approach isn't enough, @Query holds the SQL ourselves: here, "the newest users I don't follow yet", for the "Who to follow" box.
package com.example.chirp.user;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User, Long> {
// Spring Data writes these queries from the method names.
Optional<User> findByUsername(String username);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
/** Newest users that `me` does not follow yet: "Who to follow". */
@Query(value = """
SELECT u.* FROM users u
WHERE u.id <> :me
AND NOT EXISTS (SELECT 1 FROM follows f WHERE f.follower_id = :me AND f.followee_id = u.id)
ORDER BY u.id DESC
LIMIT :limit
""", nativeQuery = true)
List<User> findSuggestions(long me, int limit);
}Notice the :me and :limit parameters match the Java parameter names. That works because Spring Boot's Maven setup compiles with the -parameters flag, which keeps parameter names in the class files.
The request body and its validation
Bean Validation annotations describe what a valid request looks like. When the controller marks the parameter with @Valid, Spring checks every field before calling our code and answers 400 Bad Request if anything fails. The 72-character password limit isn't arbitrary: BCrypt only looks at the first 72 bytes of a password, so longer ones would be silently cut.
package com.example.chirp.auth;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public record RegisterRequest(
@NotBlank
@Pattern(regexp = "^[A-Za-z0-9_]{3,30}$", message = "3 to 30 letters, digits or underscores")
String username,
@NotBlank @Email @Size(max = 254)
String email,
// BCrypt only uses the first 72 bytes of a password, so longer ones are rejected.
@NotBlank @Size(min = 8, max = 72)
String password,
@NotBlank @Size(max = 50)
String displayName) {
}package com.example.chirp.auth;
import jakarta.validation.constraints.NotBlank;
public record LoginRequest(@NotBlank String username, @NotBlank String password) {
}package com.example.chirp.auth;
import com.example.chirp.user.UserSummary;
public record AuthResponse(String token, UserSummary user) {
}package com.example.chirp.user;
/** The small version of a user that appears next to posts, comments and notifications. */
public record UserSummary(long id, String username, String displayName) {
public static UserSummary from(User user) {
return new UserSummary(user.getId(), user.getUsername(), user.getDisplayName());
}
}AuthService: register and log in
The service lower-cases usernames and emails (so "Alice" and "alice" are the same account, matching the database CHECK), rejects duplicates with 409 Conflict, hashes the password with BCrypt and returns a token. @Transactional wraps the method in a database transaction: everything inside succeeds or nothing does. readOnly = true on login is a hint that lets the database and Hibernate skip work.
package com.example.chirp.auth;
import com.example.chirp.user.User;
import com.example.chirp.user.UserRepository;
import com.example.chirp.user.UserSummary;
import java.util.Locale;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
public class AuthService {
private final UserRepository users;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
public AuthService(UserRepository users, PasswordEncoder passwordEncoder, JwtService jwtService) {
this.users = users;
this.passwordEncoder = passwordEncoder;
this.jwtService = jwtService;
}
@Transactional
public AuthResponse register(RegisterRequest request) {
String username = request.username().toLowerCase(Locale.ROOT);
String email = request.email().toLowerCase(Locale.ROOT);
if (users.existsByUsername(username)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Username is already taken");
}
if (users.existsByEmail(email)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Email is already registered");
}
String hash = passwordEncoder.encode(request.password()); // never store the password itself
User user = users.save(new User(username, email, hash, request.displayName().strip()));
return new AuthResponse(jwtService.createToken(user), UserSummary.from(user));
}
@Transactional(readOnly = true)
public AuthResponse login(LoginRequest request) {
User user = users.findByUsername(request.username().toLowerCase(Locale.ROOT))
.filter(u -> passwordEncoder.matches(request.password(), u.getPasswordHash()))
// Same message for "no such user" and "wrong password": don't help attackers guess usernames.
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid username or password"));
return new AuthResponse(jwtService.createToken(user), UserSummary.from(user));
}
}Login gives the same message for an unknown username and a wrong password. A different message for each would let anyone check which usernames exist.
JWT authentication
HTTP has no memory: each request arrives on its own. After login, the browser needs a way to say "it's still me" on every request without sending the password each time. We give it a JSON Web Token: a small piece of text containing the user's id and name, plus a signature made with a secret key only the server knows. If anyone changes the contents, the signature no longer matches. Chapter 2 shows the idea in an animation; here we build it.
JwtProperties and JwtService
@ConfigurationProperties binds app.jwt.secret and app.jwt.ttl from the YAML into a record (Spring understands 24h as a Duration). JwtService creates tokens at login and checks them on every request.
package com.example.chirp.auth;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
/** Binds app.jwt.secret and app.jwt.ttl from application.yml. */
@ConfigurationProperties(prefix = "app.jwt")
public record JwtProperties(String secret, Duration ttl) {
}package com.example.chirp.auth;
import com.example.chirp.user.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import javax.crypto.SecretKey;
import org.springframework.stereotype.Service;
@Service
public class JwtService {
private final SecretKey key;
private final Duration ttl;
public JwtService(JwtProperties properties) {
// Throws WeakKeyException at startup if the secret is shorter than 256 bits.
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(properties.secret()));
this.ttl = properties.ttl();
}
public String createToken(User user) {
Instant now = Instant.now();
return Jwts.builder()
.subject(String.valueOf(user.getId()))
.claim("username", user.getUsername())
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(ttl)))
.signWith(key) // HMAC-SHA256 for a 256-bit key
.compact();
}
/** Checks the signature and expiry, then returns who the token belongs to. */
public AuthUser parse(String token) throws JwtException {
Claims claims = Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload();
return new AuthUser(Long.parseLong(claims.getSubject()), claims.get("username", String.class));
}
}package com.example.chirp.auth;
/** Who is making the request. Built from the JWT by JwtAuthFilter; no database lookup needed. */
public record AuthUser(long id, String username) {
}Which algorithm does signWith pick?
jjwt chooses the strongest HMAC algorithm the key allows. A 32-byte key (what openssl rand -base64 32 makes) signs with HS256; the 48-byte development key in application-dev.yml signs with HS384, so tokens from your dev server start with eyJhbGciOiJIUzM4NCJ9. Both are fine. A key shorter than 32 bytes is refused at start-up (see mistakes).
The filter that reads the token
A filter is code that runs before the controllers for every request, like airport security before the gates. OncePerRequestFilter guarantees it runs once per request. If the Authorization header holds a valid token, the filter tells Spring Security who the user is by putting an authentication object in the SecurityContext. If not, it does nothing; Spring Security decides later whether the URL needed a user.
package com.example.chirp.auth;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Runs once per request, before the controllers. If the request carries a valid
* "Authorization: Bearer <token>" header, it tells Spring Security who the user is.
* Not a @Component on purpose: SecurityConfig adds it to the security chain only.
*/
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
try {
AuthUser user = jwtService.parse(header.substring("Bearer ".length()));
var authentication = new UsernamePasswordAuthenticationToken(user, null, List.of());
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException | IllegalArgumentException e) {
// Bad signature, expired or malformed: stay anonymous. Protected endpoints will answer 401.
}
}
chain.doFilter(request, response);
}
}- The browser sends the token saved at login:
Authorization: Bearer eyJhbGciOi…. - The filter asks
JwtService.parseto check it: is the signature right for our secret key, and is it not expired? - The token is valid, so the filter stores
AuthUser(1, "alice")in the security context for this request. - Spring Security's rules see an authenticated user, so
/api/feedis allowed. - The controller receives the user through
@AuthenticationPrincipal AuthUser me. No database lookup was needed to know who called. - With no token, an expired one, or one whose signature doesn't match, the filter stores nothing and the rules answer
401 Unauthorizedinstead.
SecurityConfig: the rules
A @Configuration class holds @Bean methods: Spring calls each one once and keeps the result as a bean. Here we build the security filter chain:
package com.example.chirp.config;
import com.example.chirp.auth.JwtAuthFilter;
import com.example.chirp.auth.JwtService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http, JwtService jwtService) throws Exception {
http
// No cookies or server sessions: every request proves who it is with a token.
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// CSRF attacks ride on cookies the browser sends automatically. A token in the
// Authorization header is never sent automatically, so CSRF protection is not needed.
.csrf(csrf -> csrf.disable())
.httpBasic(basic -> basic.disable())
.formLogin(form -> form.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.POST, "/api/auth/register", "/api/auth/login").permitAll()
.requestMatchers("/actuator/health", "/error").permitAll()
.anyRequest().authenticated())
// Missing or bad token: answer 401 instead of redirecting to a login page.
.exceptionHandling(ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.addFilterBefore(new JwtAuthFilter(jwtService), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}- Stateless: no server sessions. The token is the only proof of identity, so any server can handle any request (important for scaling in chapter 7).
- CSRF off: cross-site request forgery tricks a browser into sending its cookies to another site. We don't use cookies for login, and browsers never add an
Authorizationheader on their own, so the attack doesn't apply. - permitAll: register, login, health and Spring's
/errorpage are public. Everything else needs a valid token. - 401 entry point: without it, Spring Security would try to send a browser to a login page. An API should just answer 401.
- The filter is created with
new, not marked@Component. Spring Boot automatically registers every filter bean with the web server as well, so a@Componentfilter would run twice: once in the security chain and once outside it.
AuthController
A @RestController maps URLs to methods and turns return values into JSON. @RequestBody reads the JSON body, @ResponseStatus(CREATED) answers 201 instead of 200.
package com.example.chirp.auth;
import com.example.chirp.user.UserService;
import com.example.chirp.user.UserSummary;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthService authService;
private final UserService userService;
public AuthController(AuthService authService, UserService userService) {
this.authService = authService;
this.userService = userService;
}
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public AuthResponse register(@Valid @RequestBody RegisterRequest request) {
return authService.register(request);
}
@PostMapping("/login")
public AuthResponse login(@Valid @RequestBody LoginRequest request) {
return authService.login(request);
}
/** Who am I? The frontend calls this on start-up to check that a saved token still works. */
@GetMapping("/me")
public UserSummary me(@AuthenticationPrincipal AuthUser me) {
return userService.summary(me.id());
}
}/me uses UserService.summary, which you will see in full in the follows section. Now try it. These are real requests and the real responses from the finished backend:
curl -i -X POST http://localhost:8080/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"alice","email":"alice@example.com","password":"correct-horse-battery","displayName":"Alice"}'HTTP/1.1 201
Content-Type: application/json
{"token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzIiwidXNlcm5hbWUiOiJhbGljZSIsImlhdCI6MTc5Mzg5NTYxMywiZXhwIjoxNzkzOTgyMDEzfQ.JA1rCG-hEYBxcT4sm0Tub8GdMw60vbsIHVpvP7qUWTw","user":{"id":3,"username":"alice","displayName":"Alice"}}curl -i -X POST http://localhost:8080/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"al","email":"alice-at-example.com","password":"short","displayName":"Alice"}'HTTP/1.1 400
Content-Type: application/problem+json
{"detail":"Some fields are invalid","instance":"/api/auth/register","status":400,"title":"Bad Request","errors":{"email":"must be a well-formed email address","password":"size must be between 8 and 72","username":"3 to 30 letters, digits or underscores"}}curl -X POST http://localhost:8080/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"Alice","email":"a2@example.com","password":"correct-horse-battery","displayName":"Alice"}'{"detail":"Username is already taken","instance":"/api/auth/register","status":409,"title":"Conflict"}curl -X POST http://localhost:8080/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"username":"alice","password":"nope-nope-nope"}'{"detail":"Invalid username or password","instance":"/api/auth/login","status":401,"title":"Unauthorized"}With the right password the answer is 200 with the same shape as registration: {"token":"eyJ…","user":{…}}. Save the token in a shell variable for the next examples:
TOKEN=$(curl -s -X POST http://localhost:8080/api/auth/login -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"correct-horse-battery"}' | jq -r .token)
curl http://localhost:8080/api/auth/me -H "Authorization: Bearer $TOKEN"{"id":3,"username":"alice","displayName":"Alice"}curl -i http://localhost:8080/api/feedHTTP/1.1 401
Content-Length: 0Paste a token into the site's JWT decoder to see what's inside: sub (the user id), username, iat (issued at) and exp (expires). Anyone can read a JWT; only the server can sign one. Never put secrets in it.
Posts: create, read and delete
The Post entity
@ManyToOne says "many posts belong to one user" and maps to the author_id foreign key. FetchType.LAZY means Hibernate loads the author only when we touch it. The three counters are marked insertable = false, updatable = false: Hibernate will never write them, because we change them with atomic SQL (explained below).
package com.example.chirp.post;
import com.example.chirp.user.User;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Many posts belong to one user. LAZY: load the author only when we ask for it.
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "author_id")
private User author;
@Column(nullable = false, length = 280)
private String content;
@Column(name = "image_url", length = 500)
private String imageUrl;
// The counters are changed with SQL (UPDATE ... SET like_count = like_count + 1),
// never by JPA, so a stale copy in memory can't overwrite a newer value.
@Column(name = "like_count", insertable = false, updatable = false)
private int likeCount;
@Column(name = "comment_count", insertable = false, updatable = false)
private int commentCount;
@Column(name = "repost_count", insertable = false, updatable = false)
private int repostCount;
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt = Instant.now();
protected Post() {
// for JPA
}
public Post(User author, String content, String imageUrl) {
this.author = author;
this.content = content;
this.imageUrl = imageUrl;
}
public Long getId() { return id; }
public User getAuthor() { return author; }
public String getContent() { return content; }
public String getImageUrl() { return imageUrl; }
public int getLikeCount() { return likeCount; }
public int getCommentCount() { return commentCount; }
public int getRepostCount() { return repostCount; }
public Instant getCreatedAt() { return createdAt; }
}PostRepository
package com.example.chirp.post;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Limit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface PostRepository extends JpaRepository<Post, Long> {
// JOIN FETCH loads each post's author in the same query (no N+1 problem).
@Query("SELECT p FROM Post p JOIN FETCH p.author WHERE p.id = :id")
Optional<Post> findWithAuthorById(long id);
@Query("SELECT p FROM Post p JOIN FETCH p.author WHERE p.id IN :ids ORDER BY p.id DESC")
List<Post> findAllWithAuthorByIdIn(Collection<Long> ids);
/** One page of a user's posts, newest first, older than the cursor. */
@Query("SELECT p FROM Post p JOIN FETCH p.author WHERE p.author.id = :authorId AND p.id < :cursor ORDER BY p.id DESC")
List<Post> findByAuthorBefore(long authorId, long cursor, Limit limit);
/** The home feed: ids of my posts and posts by people I follow, newest first. */
@Query(value = """
SELECT p.id FROM posts p
WHERE p.id < :cursor
AND (p.author_id = :userId
OR p.author_id IN (SELECT f.followee_id FROM follows f WHERE f.follower_id = :userId))
ORDER BY p.id DESC
LIMIT :limit
""", nativeQuery = true)
List<Long> findFeedIds(long userId, long cursor, int limit);
long countByAuthorId(long authorId);
// Atomic counter updates: the database adds to the current value, so two
// likes arriving at the same moment are both counted.
@Modifying
@Query(value = "UPDATE posts SET like_count = like_count + :delta WHERE id = :id", nativeQuery = true)
void addToLikeCount(long id, int delta);
@Modifying
@Query(value = "UPDATE posts SET repost_count = repost_count + :delta WHERE id = :id", nativeQuery = true)
void addToRepostCount(long id, int delta);
@Modifying
@Query(value = "UPDATE posts SET comment_count = comment_count + :delta WHERE id = :id", nativeQuery = true)
void addToCommentCount(long id, int delta);
@Query(value = "SELECT like_count FROM posts WHERE id = :id", nativeQuery = true)
int findLikeCount(long id);
@Query(value = "SELECT repost_count FROM posts WHERE id = :id", nativeQuery = true)
int findRepostCount(long id);
}Three ideas in this file are worth slowing down for:
JOIN FETCHprevents the N+1 problem. Without it, loading 20 posts runs 1 query for the posts and then, when we read each author's name, 1 more query per post: 21 queries for one page.JOIN FETCH p.authorloads posts and authors in a single query.- The feed query is native SQL (
nativeQuery = true), because it reads thefollowstable, which has no entity. It returns only ids, using the indexes from chapter 3. @Modifyingmarks a query that changes data.like_count = like_count + :deltalets PostgreSQL do the arithmetic, so simultaneous likes can't overwrite each other.
N+1 queries
Loading a page with findAllById(ids) and then reading post.getAuthor().getDisplayName() in a loop sends one extra select … from users where id=? per post.
One query
SELECT p FROM Post p JOIN FETCH p.author WHERE p.id IN :ids brings each post and its author back together. Turn on show-sql (the dev profile does) and count the lines to check.
The request and response shapes
package com.example.chirp.post;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreatePostRequest(@NotBlank @Size(max = 280) String content) {
}package com.example.chirp.post;
import com.example.chirp.user.UserSummary;
import java.time.Instant;
/** What the API sends for a post. Never return entities directly: this is the public contract. */
public record PostResponse(
long id,
String content,
String imageUrl,
Instant createdAt,
UserSummary author,
int likeCount,
int commentCount,
int repostCount,
boolean likedByMe,
boolean repostedByMe) {
public static PostResponse from(Post post, boolean likedByMe, boolean repostedByMe) {
return new PostResponse(post.getId(), post.getContent(), post.getImageUrl(), post.getCreatedAt(),
UserSummary.from(post.getAuthor()), post.getLikeCount(), post.getCommentCount(),
post.getRepostCount(), likedByMe, repostedByMe);
}
}package com.example.chirp.post;
import java.util.List;
/**
* One page of posts plus the cursor for the next page.
* nextCursor is null when there is nothing more to load.
*/
public record PostPage(List<PostResponse> items, Long nextCursor) {
public static PostPage of(List<PostResponse> items, int pageSize) {
Long next = items.size() == pageSize ? items.getLast().id() : null;
return new PostPage(items, next);
}
}package com.example.chirp.post;
public record LikeResponse(boolean liked, int likeCount) {
}package com.example.chirp.post;
public record RepostResponse(boolean reposted, int repostCount) {
}PostService
This is the biggest class in the backend because posts are where most rules live. Read create, get and delete now; the like and repost methods are explained in the likes section. Note delete: the post is loaded first and its author compared with the caller. The id in the URL is never trusted on its own.
package com.example.chirp.post;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.notification.NotificationService;
import com.example.chirp.notification.NotificationType;
import com.example.chirp.user.User;
import com.example.chirp.user.UserRepository;
import com.example.chirp.user.UserService;
import java.util.List;
import java.util.Set;
import org.springframework.data.domain.Limit;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
public class PostService {
public static final int MAX_PAGE_SIZE = 50;
private final PostRepository posts;
private final UserRepository users;
private final UserService userService;
private final LikeRepository likes;
private final RepostRepository reposts;
private final NotificationService notifications;
public PostService(PostRepository posts, UserRepository users, UserService userService, LikeRepository likes,
RepostRepository reposts, NotificationService notifications) {
this.posts = posts;
this.users = users;
this.userService = userService;
this.likes = likes;
this.reposts = reposts;
this.notifications = notifications;
}
@Transactional
public PostResponse create(AuthUser me, CreatePostRequest request) {
User author = users.findById(me.id())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User no longer exists"));
Post post = posts.save(new Post(author, request.content().strip(), null));
return PostResponse.from(post, false, false);
}
@Transactional(readOnly = true)
public PostResponse get(AuthUser me, long postId) {
Post post = posts.findWithAuthorById(postId).orElseThrow(PostService::postNotFound);
return toResponses(me, List.of(post)).getFirst();
}
@Transactional
public void delete(AuthUser me, long postId) {
Post post = posts.findById(postId).orElseThrow(PostService::postNotFound);
if (post.getAuthor().getId() != me.id()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "You can only delete your own posts");
}
posts.delete(post); // likes, reposts, comments and notifications go too (ON DELETE CASCADE)
}
@Transactional(readOnly = true)
public PostPage userPosts(AuthUser me, String username, Long cursor, int size) {
int limit = pageSize(size);
User author = userService.findByUsername(username);
List<Post> page = posts.findByAuthorBefore(author.getId(), cursorOrMax(cursor), Limit.of(limit));
return PostPage.of(toResponses(me, page), limit);
}
@Transactional
public LikeResponse like(AuthUser me, long postId) {
Post post = posts.findById(postId).orElseThrow(PostService::postNotFound);
if (likes.add(me.id(), postId)) {
posts.addToLikeCount(postId, 1);
notifications.notify(post.getAuthor().getId(), me.id(), NotificationType.LIKE, postId);
}
return new LikeResponse(true, posts.findLikeCount(postId));
}
@Transactional
public LikeResponse unlike(AuthUser me, long postId) {
posts.findById(postId).orElseThrow(PostService::postNotFound);
if (likes.remove(me.id(), postId)) {
posts.addToLikeCount(postId, -1);
}
return new LikeResponse(false, posts.findLikeCount(postId));
}
@Transactional
public RepostResponse repost(AuthUser me, long postId) {
Post post = posts.findById(postId).orElseThrow(PostService::postNotFound);
if (reposts.add(me.id(), postId)) {
posts.addToRepostCount(postId, 1);
notifications.notify(post.getAuthor().getId(), me.id(), NotificationType.REPOST, postId);
}
return new RepostResponse(true, posts.findRepostCount(postId));
}
@Transactional
public RepostResponse unrepost(AuthUser me, long postId) {
posts.findById(postId).orElseThrow(PostService::postNotFound);
if (reposts.remove(me.id(), postId)) {
posts.addToRepostCount(postId, -1);
}
return new RepostResponse(false, posts.findRepostCount(postId));
}
/** Adds "did I like / repost this?" to a list of posts with two queries in total, not two per post. */
public List<PostResponse> toResponses(AuthUser me, List<Post> page) {
List<Long> ids = page.stream().map(Post::getId).toList();
Set<Long> liked = likes.findLikedPostIds(me.id(), ids);
Set<Long> reposted = reposts.findRepostedPostIds(me.id(), ids);
return page.stream()
.map(p -> PostResponse.from(p, liked.contains(p.getId()), reposted.contains(p.getId())))
.toList();
}
public static int pageSize(int requested) {
return Math.clamp(requested, 1, MAX_PAGE_SIZE);
}
public static long cursorOrMax(Long cursor) {
return cursor == null ? Long.MAX_VALUE : cursor;
}
static ResponseStatusException postNotFound() {
return new ResponseStatusException(HttpStatus.NOT_FOUND, "Post not found");
}
}PostService uses two repositories you haven't seen yet, LikeRepository and RepostRepository, and NotificationService. They follow in the next sections. Until all files are in place the project won't compile, which is normal when building a feature set in order.
PostController
package com.example.chirp.post;
import com.example.chirp.auth.AuthUser;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public PostResponse create(@AuthenticationPrincipal AuthUser me, @Valid @RequestBody CreatePostRequest request) {
return postService.create(me, request);
}
@GetMapping("/{id}")
public PostResponse get(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
return postService.get(me, id);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
postService.delete(me, id);
}
@PostMapping("/{id}/like")
public LikeResponse like(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
return postService.like(me, id);
}
@DeleteMapping("/{id}/like")
public LikeResponse unlike(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
return postService.unlike(me, id);
}
@PostMapping("/{id}/repost")
public RepostResponse repost(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
return postService.repost(me, id);
}
@DeleteMapping("/{id}/repost")
public RepostResponse unrepost(@AuthenticationPrincipal AuthUser me, @PathVariable long id) {
return postService.unrepost(me, id);
}
}@PathVariable long id takes the {id} part of the URL. The methods are deliberately thin: read the request, call the service, return the result. Real responses:
POST /api/posts
Authorization: Bearer eyJ…
Content-Type: application/json
{"content":"Building a Twitter clone with Spring Boot and React."}HTTP/1.1 201
Content-Type: application/json
{"id":6,"content":"Building a Twitter clone with Spring Boot and React.","imageUrl":null,"createdAt":"2026-11-05T16:20:13.942706506Z","author":{"id":3,"username":"alice","displayName":"Alice"},"likeCount":0,"commentCount":0,"repostCount":0,"likedByMe":false,"repostedByMe":false}With show-sql on, the dev console shows exactly the two statements this needed (load the author, insert the post):
Hibernate: select u1_0.id,u1_0.bio,u1_0.created_at,u1_0.display_name,u1_0.email,u1_0.password_hash,u1_0.username from users u1_0 where u1_0.id=?
Hibernate: insert into posts (author_id,content,created_at,image_url) values (?,?,?,?)DELETE /api/posts/5
Authorization: Bearer (bob's token)HTTP/1.1 403
Content-Type: application/problem+json
{"detail":"You can only delete your own posts","instance":"/api/posts/5","status":403,"title":"Forbidden"}GET /api/posts/999999
Authorization: Bearer eyJ…{"detail":"Post not found","instance":"/api/posts/999999","status":404,"title":"Not Found"}POST /api/posts
Content-Type: application/json
{"content": }{"detail":"Failed to read request","instance":"/api/posts","status":400,"title":"Bad Request"}Follow and unfollow
The follows table is just pairs of user ids. A JPA entity for it would need a composite-key class and brings nothing in return, so we use JdbcClient, Spring's small, fluent helper for plain SQL. It joins the same transaction as the JPA repositories, so mixing them is safe.
package com.example.chirp.user;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
/**
* The follows table is just pairs of ids, so plain SQL is simpler than a JPA entity.
* JdbcClient joins the same transaction as the JPA repositories.
*/
@Repository
public class FollowRepository {
private final JdbcClient jdbc;
public FollowRepository(JdbcClient jdbc) {
this.jdbc = jdbc;
}
/** @return true if a new row was added, false if already following. */
public boolean follow(long followerId, long followeeId) {
return jdbc.sql("INSERT INTO follows (follower_id, followee_id) VALUES (?, ?) ON CONFLICT DO NOTHING")
.params(followerId, followeeId)
.update() == 1;
}
public boolean unfollow(long followerId, long followeeId) {
return jdbc.sql("DELETE FROM follows WHERE follower_id = ? AND followee_id = ?")
.params(followerId, followeeId)
.update() == 1;
}
public boolean isFollowing(long followerId, long followeeId) {
return jdbc.sql("SELECT EXISTS (SELECT 1 FROM follows WHERE follower_id = ? AND followee_id = ?)")
.params(followerId, followeeId)
.query(Boolean.class)
.single();
}
public long countFollowers(long userId) {
return jdbc.sql("SELECT count(*) FROM follows WHERE followee_id = ?").param(userId).query(Long.class).single();
}
public long countFollowing(long userId) {
return jdbc.sql("SELECT count(*) FROM follows WHERE follower_id = ?").param(userId).query(Long.class).single();
}
}ON CONFLICT DO NOTHING makes following idempotent: doing it twice has the same effect as once, because the primary key (follower_id, followee_id) refuses the duplicate quietly. update() returns how many rows changed, so == 1 tells us whether this was a new follow, and only then do we send a notification.
package com.example.chirp.user;
import java.time.Instant;
public record ProfileResponse(
long id,
String username,
String displayName,
String bio,
Instant createdAt,
long followerCount,
long followingCount,
long postCount,
boolean followedByMe) {
}package com.example.chirp.user;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.notification.NotificationService;
import com.example.chirp.notification.NotificationType;
import com.example.chirp.post.PostRepository;
import java.util.List;
import java.util.Locale;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
public class UserService {
private final UserRepository users;
private final FollowRepository follows;
private final PostRepository posts;
private final NotificationService notifications;
public UserService(UserRepository users, FollowRepository follows, PostRepository posts,
NotificationService notifications) {
this.users = users;
this.follows = follows;
this.posts = posts;
this.notifications = notifications;
}
public User findByUsername(String username) {
return users.findByUsername(username.toLowerCase(Locale.ROOT))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
}
@Transactional(readOnly = true)
public UserSummary summary(long userId) {
return users.findById(userId).map(UserSummary::from)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User no longer exists"));
}
@Transactional(readOnly = true)
public ProfileResponse profile(AuthUser me, String username) {
User user = findByUsername(username);
long id = user.getId();
return new ProfileResponse(id, user.getUsername(), user.getDisplayName(), user.getBio(), user.getCreatedAt(),
follows.countFollowers(id), follows.countFollowing(id), posts.countByAuthorId(id),
follows.isFollowing(me.id(), id));
}
@Transactional
public void follow(AuthUser me, String username) {
User target = findByUsername(username);
if (target.getId() == me.id()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You cannot follow yourself");
}
if (follows.follow(me.id(), target.getId())) {
notifications.notify(target.getId(), me.id(), NotificationType.FOLLOW, null);
}
}
@Transactional
public void unfollow(AuthUser me, String username) {
follows.unfollow(me.id(), findByUsername(username).getId());
}
@Transactional(readOnly = true)
public List<UserSummary> suggestions(AuthUser me) {
return users.findSuggestions(me.id(), 5).stream().map(UserSummary::from).toList();
}
}package com.example.chirp.user;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.post.PostPage;
import com.example.chirp.post.PostService;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
private final PostService postService;
public UserController(UserService userService, PostService postService) {
this.userService = userService;
this.postService = postService;
}
@GetMapping("/suggestions")
public List<UserSummary> suggestions(@AuthenticationPrincipal AuthUser me) {
return userService.suggestions(me);
}
@GetMapping("/{username}")
public ProfileResponse profile(@AuthenticationPrincipal AuthUser me, @PathVariable String username) {
return userService.profile(me, username);
}
@GetMapping("/{username}/posts")
public PostPage posts(@AuthenticationPrincipal AuthUser me, @PathVariable String username,
@RequestParam(required = false) Long cursor,
@RequestParam(defaultValue = "20") int size) {
return postService.userPosts(me, username, cursor, size);
}
@PostMapping("/{username}/follow")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void follow(@AuthenticationPrincipal AuthUser me, @PathVariable String username) {
userService.follow(me, username);
}
@DeleteMapping("/{username}/follow")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void unfollow(@AuthenticationPrincipal AuthUser me, @PathVariable String username) {
userService.unfollow(me, username);
}
}/suggestions is declared before /{username} only for readability; Spring always prefers the literal path over the variable one. Bob follows Alice and reads her profile (real responses):
curl -i -X POST http://localhost:8080/api/users/alice/follow -H "Authorization: Bearer $BOB"
curl http://localhost:8080/api/users/alice -H "Authorization: Bearer $BOB"HTTP/1.1 204
{
"id": 3,
"username": "alice",
"displayName": "Alice",
"bio": "",
"createdAt": "2026-11-05T16:20:13.516070Z",
"followerCount": 1,
"followingCount": 0,
"postCount": 2,
"followedByMe": true
}Likes, reposts and comments
Likes and reposts work exactly like follows: a pair table with a composite primary key, and ON CONFLICT DO NOTHING.
package com.example.chirp.post;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
@Repository
public class LikeRepository {
private final JdbcClient jdbc;
public LikeRepository(JdbcClient jdbc) {
this.jdbc = jdbc;
}
/** @return true if this is a new like (liking twice does nothing). */
public boolean add(long userId, long postId) {
return jdbc.sql("INSERT INTO likes (user_id, post_id) VALUES (?, ?) ON CONFLICT DO NOTHING")
.params(userId, postId)
.update() == 1;
}
public boolean remove(long userId, long postId) {
return jdbc.sql("DELETE FROM likes WHERE user_id = ? AND post_id = ?")
.params(userId, postId)
.update() == 1;
}
/** Which of these posts has the user liked? One query for a whole page of posts. */
public Set<Long> findLikedPostIds(long userId, Collection<Long> postIds) {
if (postIds.isEmpty()) return Set.of();
return new HashSet<>(jdbc.sql("SELECT post_id FROM likes WHERE user_id = :userId AND post_id IN (:postIds)")
.param("userId", userId)
.param("postIds", postIds)
.query(Long.class)
.list());
}
}package com.example.chirp.post;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
@Repository
public class RepostRepository {
private final JdbcClient jdbc;
public RepostRepository(JdbcClient jdbc) {
this.jdbc = jdbc;
}
public boolean add(long userId, long postId) {
return jdbc.sql("INSERT INTO reposts (user_id, post_id) VALUES (?, ?) ON CONFLICT DO NOTHING")
.params(userId, postId)
.update() == 1;
}
public boolean remove(long userId, long postId) {
return jdbc.sql("DELETE FROM reposts WHERE user_id = ? AND post_id = ?")
.params(userId, postId)
.update() == 1;
}
public Set<Long> findRepostedPostIds(long userId, Collection<Long> postIds) {
if (postIds.isEmpty()) return Set.of();
return new HashSet<>(jdbc.sql("SELECT post_id FROM reposts WHERE user_id = :userId AND post_id IN (:postIds)")
.param("userId", userId)
.param("postIds", postIds)
.query(Long.class)
.list());
}
}findLikedPostIds answers "which of these 20 posts did I like?" in one query. PostService.toResponses calls it once per page, so likedByMe costs one query for the whole page, not one per post. Here is the like method again:
public LikeResponse like(AuthUser me, long postId) {
Post post = posts.findById(postId).orElseThrow(PostService::postNotFound);
if (likes.add(me.id(), postId)) {
posts.addToLikeCount(postId, 1);
notifications.notify(post.getAuthor().getId(), me.id(), NotificationType.LIKE, postId);
}
return new LikeResponse(true, posts.findLikeCount(postId));Why the counter is updated with SQL
We store like_count on the post so the feed doesn't need to count rows for every post it shows. The danger is updating it the obvious way: read the number into Java, add one, save it. Run both versions below. Two people, A and B, like a post with 7 likes at the same moment.
What happens
- Pick a version to run.
like_count in the database
Two likes should make 9.
// Atomic counter updates: the database adds to the current value, so two
// likes arriving at the same moment are both counted.
@Modifying
@Query(value = "UPDATE posts SET like_count = like_count + :delta WHERE id = :id", nativeQuery = true)
void addToLikeCount(long id, int delta);An UPDATE locks the row it changes until the transaction ends, so a second UPDATE on the same row waits and then adds to the new value. And since likes.add only returns true for a new row, clicking twice can't count twice either.
Comments
Comments are real entities (they have their own id and text), so they use JPA. A comment belongs to a post and to an author: two @ManyToOne relations.
package com.example.chirp.comment;
import com.example.chirp.post.Post;
import com.example.chirp.user.User;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "post_id")
private Post post;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "author_id")
private User author;
@Column(nullable = false, length = 280)
private String content;
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt = Instant.now();
protected Comment() {
// for JPA
}
public Comment(Post post, User author, String content) {
this.post = post;
this.author = author;
this.content = content;
}
public Long getId() { return id; }
public Post getPost() { return post; }
public User getAuthor() { return author; }
public String getContent() { return content; }
public Instant getCreatedAt() { return createdAt; }
}Page<Comment> is Spring Data's offset pagination. It runs our query with LIMIT/OFFSET, and a second countQuery for the total, so the response can say "page 1 of 3". We need a separate count query because the main one uses JOIN FETCH, which can't be counted.
package com.example.chirp.comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface CommentRepository extends JpaRepository<Comment, Long> {
// Page<T> runs two queries: this one, and countQuery for the total number of comments.
@Query(value = "SELECT c FROM Comment c JOIN FETCH c.author WHERE c.post.id = :postId ORDER BY c.id",
countQuery = "SELECT count(c) FROM Comment c WHERE c.post.id = :postId")
Page<Comment> findByPostId(long postId, Pageable pageable);
}package com.example.chirp.comment;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateCommentRequest(@NotBlank @Size(max = 280) String content) {
}package com.example.chirp.comment;
import com.example.chirp.user.UserSummary;
import java.time.Instant;
public record CommentResponse(long id, long postId, String content, Instant createdAt, UserSummary author) {
public static CommentResponse from(Comment comment) {
return new CommentResponse(comment.getId(), comment.getPost().getId(), comment.getContent(),
comment.getCreatedAt(), UserSummary.from(comment.getAuthor()));
}
}package com.example.chirp.comment;
import java.util.List;
/** Offset pagination: page numbers and a total, like "page 2 of 5". */
public record CommentPage(List<CommentResponse> items, int page, int totalPages, long totalItems) {
}package com.example.chirp.comment;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.notification.NotificationService;
import com.example.chirp.notification.NotificationType;
import com.example.chirp.post.Post;
import com.example.chirp.post.PostRepository;
import com.example.chirp.post.PostService;
import com.example.chirp.user.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
public class CommentService {
private final CommentRepository comments;
private final PostRepository posts;
private final UserRepository users;
private final NotificationService notifications;
public CommentService(CommentRepository comments, PostRepository posts, UserRepository users,
NotificationService notifications) {
this.comments = comments;
this.posts = posts;
this.users = users;
this.notifications = notifications;
}
@Transactional(readOnly = true)
public CommentPage list(long postId, int page, int size) {
if (!posts.existsById(postId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Post not found");
}
Page<Comment> result = comments.findByPostId(postId,
PageRequest.of(Math.max(page, 0), PostService.pageSize(size)));
return new CommentPage(result.map(CommentResponse::from).getContent(),
result.getNumber(), result.getTotalPages(), result.getTotalElements());
}
@Transactional
public CommentResponse add(AuthUser me, long postId, CreateCommentRequest request) {
Post post = posts.findById(postId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Post not found"));
Comment comment = comments.save(new Comment(post, users.getReferenceById(me.id()), request.content().strip()));
posts.addToCommentCount(postId, 1);
notifications.notify(post.getAuthor().getId(), me.id(), NotificationType.COMMENT, postId);
return CommentResponse.from(comment);
}
}package com.example.chirp.comment;
import com.example.chirp.auth.AuthUser;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/posts/{postId}/comments")
public class CommentController {
private final CommentService commentService;
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
@GetMapping
public CommentPage list(@PathVariable long postId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return commentService.list(postId, page, size);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CommentResponse add(@AuthenticationPrincipal AuthUser me, @PathVariable long postId,
@Valid @RequestBody CreateCommentRequest request) {
return commentService.add(me, postId, request);
}
}Real responses for a like, a reply, and the list of replies:
{"liked":true,"likeCount":1}
{"id":2,"postId":5,"content":"Welcome to Chirp!","createdAt":"2026-11-05T16:20:13.983531905Z","author":{"id":4,"username":"bob","displayName":"Bob"}}
{
"items": [
{
"id": 2,
"postId": 5,
"content": "Welcome to Chirp!",
"createdAt": "2026-11-05T16:20:13.983532Z",
"author": { "id": 4, "username": "bob", "displayName": "Bob" }
}
],
"page": 0,
"totalPages": 1,
"totalItems": 1
}The two createdAt values differ in their last digits: Java's clock has nanoseconds, PostgreSQL stores microseconds. The first comes from the object we just created, the second from the database.
Notifications
Each like, repost, reply or follow creates one row for the person it happened to. @Enumerated(EnumType.STRING) stores the type as text ('LIKE'), which is readable in SQL and safe if we reorder the enum later (storing numbers would silently change meaning).
package com.example.chirp.notification;
public enum NotificationType {
LIKE, COMMENT, FOLLOW, REPOST
}package com.example.chirp.notification;
import com.example.chirp.user.User;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "notifications")
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "recipient_id", nullable = false)
private Long recipientId;
// Who did it: "alice liked your post"
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "actor_id")
private User actor;
@Enumerated(EnumType.STRING) // stored as 'LIKE', not as a number
@Column(nullable = false, length = 20)
private NotificationType type;
@Column(name = "post_id")
private Long postId; // null for FOLLOW
@Column(name = "is_read", nullable = false)
private boolean read;
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt = Instant.now();
protected Notification() {
// for JPA
}
public Notification(Long recipientId, User actor, NotificationType type, Long postId) {
this.recipientId = recipientId;
this.actor = actor;
this.type = type;
this.postId = postId;
}
public Long getId() { return id; }
public Long getRecipientId() { return recipientId; }
public User getActor() { return actor; }
public NotificationType getType() { return type; }
public Long getPostId() { return postId; }
public boolean isRead() { return read; }
public Instant getCreatedAt() { return createdAt; }
}package com.example.chirp.notification;
import java.util.List;
import org.springframework.data.domain.Limit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface NotificationRepository extends JpaRepository<Notification, Long> {
@Query("SELECT n FROM Notification n JOIN FETCH n.actor WHERE n.recipientId = :recipientId ORDER BY n.id DESC")
List<Notification> findLatest(long recipientId, Limit limit);
long countByRecipientIdAndReadFalse(long recipientId);
@Modifying
@Query("UPDATE Notification n SET n.read = true WHERE n.recipientId = :recipientId AND n.read = false")
int markAllRead(long recipientId);
}package com.example.chirp.notification;
import com.example.chirp.user.UserSummary;
import java.time.Instant;
public record NotificationResponse(long id, NotificationType type, UserSummary actor, Long postId, boolean read,
Instant createdAt) {
public static NotificationResponse from(Notification n) {
return new NotificationResponse(n.getId(), n.getType(), UserSummary.from(n.getActor()), n.getPostId(),
n.isRead(), n.getCreatedAt());
}
}package com.example.chirp.notification;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.user.UserRepository;
import java.util.List;
import org.springframework.data.domain.Limit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class NotificationService {
private final NotificationRepository notifications;
private final UserRepository users;
public NotificationService(NotificationRepository notifications, UserRepository users) {
this.notifications = notifications;
this.users = users;
}
/** Records "actor did something to recipient". Called inside the like/follow/comment transaction. */
@Transactional
public void notify(long recipientId, long actorId, NotificationType type, Long postId) {
if (recipientId == actorId) {
return; // liking your own post is not news
}
notifications.save(new Notification(recipientId, users.getReferenceById(actorId), type, postId));
}
@Transactional(readOnly = true)
public List<NotificationResponse> latest(AuthUser me) {
return notifications.findLatest(me.id(), Limit.of(30)).stream().map(NotificationResponse::from).toList();
}
@Transactional(readOnly = true)
public long unreadCount(AuthUser me) {
return notifications.countByRecipientIdAndReadFalse(me.id());
}
@Transactional
public void markAllRead(AuthUser me) {
notifications.markAllRead(me.id());
}
}notify is called from inside the like, follow or comment transaction. If saving the like fails, the notification is rolled back with it, so nobody is told about a like that doesn't exist. Liking your own post creates nothing.
package com.example.chirp.notification;
import com.example.chirp.auth.AuthUser;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/notifications")
public class NotificationController {
private final NotificationService notificationService;
public NotificationController(NotificationService notificationService) {
this.notificationService = notificationService;
}
@GetMapping
public List<NotificationResponse> latest(@AuthenticationPrincipal AuthUser me) {
return notificationService.latest(me);
}
@GetMapping("/unread-count")
public Map<String, Long> unreadCount(@AuthenticationPrincipal AuthUser me) {
return Map.of("count", notificationService.unreadCount(me));
}
@PostMapping("/read")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void markAllRead(@AuthenticationPrincipal AuthUser me) {
notificationService.markAllRead(me);
}
}[
{
"id": 7,
"type": "COMMENT",
"actor": { "id": 4, "username": "bob", "displayName": "Bob" },
"postId": 5,
"read": false,
"createdAt": "2026-11-05T16:20:13.985976Z"
},
{
"id": 5,
"type": "FOLLOW",
"actor": { "id": 4, "username": "bob", "displayName": "Bob" },
"postId": null,
"read": false,
"createdAt": "2026-11-05T16:20:13.955572Z"
}
]The home feed
We build the feed the simplest correct way, called pull (or fan-out on read): every time you open it, ask PostgreSQL for the newest posts by you and the people you follow. It is always up to date and needs no extra storage. Chapter 6 adds the push model with Redis and compares them.
- Query 1 asks only for ids: posts by me or by anyone in
followswhere I'm the follower, older than the cursor, newest first, 20 of them. - The indexes from chapter 3 make this fast: it reads ids, never whole rows.
- Query 2 loads those 20 posts with their authors in one go.
- Two small queries mark which of the 20 I liked and reposted.
- Four queries in total, whatever the page size: never one per post.
package com.example.chirp.feed;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.post.Post;
import com.example.chirp.post.PostPage;
import com.example.chirp.post.PostRepository;
import com.example.chirp.post.PostService;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* The home feed, "pull" style: each time you open it, we ask the database for the
* newest posts by you and the people you follow. Chapter 6 compares this with "push".
*/
@Service
public class FeedService {
private final PostRepository posts;
private final PostService postService;
public FeedService(PostRepository posts, PostService postService) {
this.posts = posts;
this.postService = postService;
}
@Transactional(readOnly = true)
public PostPage homeFeed(AuthUser me, Long cursor, int size) {
int limit = PostService.pageSize(size);
// Query 1: which posts? (only ids, using the indexes)
List<Long> ids = posts.findFeedIds(me.id(), PostService.cursorOrMax(cursor), limit);
// Query 2: load those posts with their authors.
List<Post> page = ids.isEmpty() ? List.of() : posts.findAllWithAuthorByIdIn(ids);
return PostPage.of(postService.toResponses(me, page), limit);
}
}package com.example.chirp.feed;
import com.example.chirp.auth.AuthUser;
import com.example.chirp.post.PostPage;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeedController {
private final FeedService feedService;
public FeedController(FeedService feedService) {
this.feedService = feedService;
}
/** GET /api/feed?cursor=123&size=20 */
@GetMapping("/api/feed")
public PostPage feed(@AuthenticationPrincipal AuthUser me,
@RequestParam(required = false) Long cursor,
@RequestParam(defaultValue = "20") int size) {
return feedService.homeFeed(me, cursor, size);
}
}Bob's feed after following Alice, asking for one post at a time (real response):
curl "http://localhost:8080/api/feed?size=1" -H "Authorization: Bearer $BOB"{
"items": [
{
"id": 6,
"content": "Building a Twitter clone with Spring Boot and React.",
"imageUrl": null,
"createdAt": "2026-11-05T16:20:13.942707Z",
"author": { "id": 3, "username": "alice", "displayName": "Alice" },
"likeCount": 0,
"commentCount": 0,
"repostCount": 0,
"likedByMe": false,
"repostedByMe": false
}
],
"nextCursor": 6
}Pagination: cursors versus page numbers
Nobody loads every post at once. We send one page and let the app ask for more. There are two ways to say "the next page":
Offset: ?page=2
ORDER BY id DESC LIMIT 20 OFFSET 40. Easy and gives "page 3 of 7", but the database still walks past the first 40 rows, and if new posts arrive while you read, everything shifts: you see some posts twice.
Cursor: ?cursor=41
WHERE id < 41 ORDER BY id DESC LIMIT 20. "Give me 20 posts older than the last one I saw." New posts can't shift it, and the index jumps straight to the right place.
This works because ids only grow over time, so "older" means "smaller id". PostPage.of sets nextCursor to the last id when the page is full, or null when there is nothing more. PostService.pageSize keeps the size between 1 and 50 with Java 21's Math.clamp, so nobody can ask for a million posts at once. See the difference for yourself:
The feed holds posts 10 down to 1, three per page.
Offset pages
–Cursor pages
–So why do comments use page numbers? A reply thread is short, read oldest-first, and readers like to see "page 1 of 3". The duplicate problem is real there too, which is why the React app in chapter 5 skips comments it already shows. Choosing per list, instead of using one style everywhere, is the kind of decision this course wants you to make consciously.
Turning errors into clean JSON
When something goes wrong, the React app needs a predictable shape it can show to the user. @RestControllerAdvice creates one class that handles exceptions from every controller. By extending ResponseEntityExceptionHandler, we get Spring's standard handling of bad JSON, unknown URLs and ResponseStatusException (which our services throw for 401/403/404/409) for free, and customise two cases.
package com.example.chirp.common;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/**
* Turns exceptions into consistent JSON errors (RFC 9457 "problem details").
* The base class already handles ResponseStatusException, 404s, bad JSON and more.
*/
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
/** @Valid failed: list every bad field so the form can show the messages next to the inputs. */
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Map<String, String> errors = new TreeMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(error -> errors.putIfAbsent(error.getField(), error.getDefaultMessage()));
ProblemDetail problem = ex.getBody();
problem.setDetail("Some fields are invalid");
problem.setProperty("errors", errors);
return handleExceptionInternal(ex, problem, headers, status, request);
}
/** A UNIQUE or foreign key constraint said no, e.g. two people registering the same name at once. */
@ExceptionHandler(DataIntegrityViolationException.class)
ProblemDetail handleConflict(DataIntegrityViolationException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "That conflicts with existing data");
}
}- Validation: instead of one generic message, list every bad field in
errors, sorted by name (TreeMap), so the sign-up form can show each message under its input. - Constraint violations: if two people register the same name at the exact same moment, both pass the
existsByUsernamecheck, and the database'sUNIQUEconstraint stops the second. Without this handler that would be a 500 error; now it's a 409.
Every error has the same fields: status, title, a human detail and the instance (the path). You saw them in every 4xx response above.
Try the API
The explorer below is simulated in your browser: no server is involved, but it follows the same rules and returns the same JSON format as the real backend you just built, so you can explore it before running anything. Start with Log in as alice, then try the other examples, or edit the method, path and body yourself.
Pick an example and press Send.
Against your real server, the same requests with curl. The complete end-to-end script that registers two users and checks 25 behaviours is in chapter 8.
# a post, a follow, a like and a reply (ALICE and BOB hold tokens from /api/auth/login)
curl -X POST http://localhost:8080/api/posts -H "Authorization: Bearer $ALICE" \
-H 'Content-Type: application/json' -d '{"content":"Hello, Chirp! My first post."}'
curl -X POST http://localhost:8080/api/users/alice/follow -H "Authorization: Bearer $BOB"
curl -X POST http://localhost:8080/api/posts/5/like -H "Authorization: Bearer $BOB"
curl -X POST http://localhost:8080/api/posts/5/comments -H "Authorization: Bearer $BOB" \
-H 'Content-Type: application/json' -d '{"content":"Welcome to Chirp!"}'
curl http://localhost:8080/api/notifications/unread-count -H "Authorization: Bearer $ALICE"{"count":3}| Method | Path | Does | Success |
|---|---|---|---|
| POST | /api/auth/register, /api/auth/login | Create account / log in, returns a token | 201 / 200 |
| GET | /api/auth/me | Who am I? | 200 |
| POST | /api/posts | Write a post | 201 |
| GET DELETE | /api/posts/{id} | Read / delete a post (author only) | 200 / 204 |
| POST DELETE | /api/posts/{id}/like, …/repost | Like, unlike, repost, undo | 200 |
| GET POST | /api/posts/{id}/comments?page= | List / add replies | 200 / 201 |
| GET | /api/feed?cursor=&size= | Home feed | 200 |
| GET | /api/users/{username}, …/posts, /api/users/suggestions | Profile, a user's posts, who to follow | 200 |
| POST DELETE | /api/users/{username}/follow | Follow / unfollow | 204 |
| GET POST | /api/notifications, …/unread-count, …/read | Latest 30, unread count, mark all read | 200 / 204 |
Common mistakes and how to fix them
Start-up fails with 'url' must start with "jdbc"
Spring couldn't fill in ${DB_URL}, so it used the text itself as the URL. You started the app without the dev profile and without environment variables.
Fix: ./mvnw spring-boot:run -Dspring-boot.run.profiles=dev, or in your IDE's run configuration set the active profile to dev.
WeakKeyException at start-up
A JWT secret shorter than 32 bytes is rejected. The real message: WeakKeyException: The specified key byte array is 96 bits which is not secure enough for any JWT HMAC-SHA algorithm … MUST have a size >= 256 bits.
Fix: generate a proper key with openssl rand -base64 32. Never use a word or a short phrase as a signing key.
Marking JwtAuthFilter as @Component
Spring Boot registers every filter bean with the web server, so the filter runs twice per request: once in the security chain and once outside it. It mostly "works", which makes it hard to notice.
Fix: create it with new inside SecurityConfig, as we do. If it must be a bean, add a FilterRegistrationBean with setEnabled(false).
LazyInitializationException: could not initialize proxy - no Session
With open-in-view: false, the database session closes when the @Transactional service method returns. Touching post.getAuthor().getDisplayName() after that, in a controller for example, fails.
Fix: build the DTO inside the service method (we do: PostResponse.from is called in the service), and load what you need with JOIN FETCH.
N+1 queries that make pages slow
Loading a list and then reading a lazy relation in a loop runs one query per item. It's invisible in small tests and painful with real data.
Fix: keep show-sql on in development and count the queries per request. Use JOIN FETCH and "IN (:ids)" queries for whole pages.
Returning entities from controllers
return userRepository.findById(id) sends passwordHash and email to anyone who asks, can loop forever on two-way relations, and ties your API to your tables.
Fix: return records (DTOs) built for the API, like UserSummary and PostResponse.
Counting with read-modify-write
post.setLikeCount(post.getLikeCount() + 1) loses updates when requests overlap, as the simulator showed.
Fix: UPDATE posts SET like_count = like_count + 1, and a unique key on (user_id, post_id) so a like can only be added once.
"Name for argument … not specified" in a repository
Named parameters like :userId are matched to Java parameter names, which only exist in the compiled class if the compiler ran with -parameters. Spring Boot's Maven parent sets it, but some IDE or custom build setups don't.
Fix: build with Maven, enable "-parameters" in your IDE's compiler settings, or add @Param("userId") to each parameter.
CORS errors when testing from a web page
A page served from localhost:5173 calling http://localhost:8080/api/… directly is a different origin, so the browser blocks the response unless the server sends CORS headers.
Fix: don't call port 8080 from the browser. In chapter 5 Vite forwards /api to Spring Boot, and in production nginx does the same, so the browser only ever talks to one origin and no CORS settings are needed.
Key takeaways
- Requests pass through filters → controller → service → repository → database; each layer has one job.
- Spring creates beans and injects them through constructors; we never
newa service or repository. - Flyway owns the schema, Hibernate only validates it, and secrets come from the environment.
- Passwords are BCrypt hashes; a signed JWT proves identity on every request without a database lookup.
- Rules live in services: check ownership, make actions idempotent, and let SQL do counter arithmetic.
- Load whole pages with a fixed number of queries (JOIN FETCH, IN lists), and paginate feeds with cursors.
- Return DTOs, never entities, and send every error in the same JSON shape.
Check your understanding
Where should the rule "only the author can delete a post" live?
- In the React app, by hiding the Delete button
- In the service, by comparing the post's author with the caller
- In the controller's URL mapping
post.getAuthor().getId() with the id from the verified token.Why doesn't JwtAuthFilter load the user from the database on every request?
- Spring Security forbids database access in filters
- The user table is cached automatically
- The signed token already proves the id and username, so checking the signature is enough
Bob calls POST /api/users/alice/follow twice. What happens?
- 204 both times; one row exists and Alice gets one notification
- The second call fails with 409 Conflict
- Two rows are saved and the follower count is 2
ON CONFLICT DO NOTHING makes the second insert change zero rows, follow() returns false, and no second notification is sent. Idempotent actions are safe to retry, which matters on flaky mobile networks.Why is the feed paginated with ?cursor= instead of ?page=?
- Cursors are required by Spring Data
- New posts arriving at the top don't shift a cursor, so nothing is shown twice, and the index finds the start directly
- Cursors allow jumping to any page number
Exercise: let people delete their replies
Add DELETE /api/posts/{postId}/comments/{commentId}. Only the comment's author may delete it, and the post's comment_count must go down by one. Return 204. Think about: which layer checks ownership, what happens if the comment belongs to a different post, and which status codes you return.
Show a sample answer
In CommentService:
@Transactional
public void delete(AuthUser me, long postId, long commentId) {
Comment comment = comments.findById(commentId)
.filter(c -> c.getPost().getId() == postId) // the comment must belong to this post
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Comment not found"));
if (comment.getAuthor().getId() != me.id()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "You can only delete your own replies");
}
comments.delete(comment);
posts.addToCommentCount(postId, -1); // atomic, like the likes counter
}In CommentController:
@DeleteMapping("/{commentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@AuthenticationPrincipal AuthUser me, @PathVariable long postId, @PathVariable long commentId) {
commentService.delete(me, postId, commentId);
}Note that the "wrong post" case returns 404, not 403: from that URL's point of view the comment doesn't exist. Reading getPost().getId() and getAuthor().getId() on lazy relations is safe, because Hibernate knows the ids without loading the rows.
This answer was compiled into the chapter's project and tried against PostgreSQL: wrong post → 404, someone else's reply → 403, your own → 204, and commentCount drops back to 0. Add the DeleteMapping import to the controller.
Finished this chapter? Tick it off. Progress is saved in this browser only.