Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ A collection of hands-on coding interview projects organized by language. Each p
> **Backend concepts:** [java/concepts/](java/concepts/) is a different kind of project: not a timed
> round, but one concept taught step by step. Each is broken first (you run it and watch the problem
> happen), has challenge tasks and a guided version, tests as acceptance criteria, and `start/` and
> `solution/` folders side by side. There are eleven so far, numbered in the suggested order from
> `01-transactional` to `11-pagination`: see the [list](java/concepts/README.md).
> `solution/` folders side by side. There are fifteen so far, numbered in the suggested order from
> `01-transactional` to `15-equals-and-hashcode`: see the [list](java/concepts/README.md).

## Structure

Expand Down Expand Up @@ -97,7 +97,7 @@ interview-prep/
│ ├── karat-drills/
│ ├── secret-storage/
│ ├── concepts/
│ │ └── junior-mid/ (01-transactional ... 11-pagination)
│ │ └── junior-mid/ (01-transactional ... 15-equals-and-hashcode)
│ ├── DELIVERY_HERO.md
│ └── KARAT.md
├── python/
Expand Down
4 changes: 4 additions & 0 deletions java/concepts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ under [`java/`](../).
| 09 | Junior / mid | [Isolation levels](junior-mid/09-isolation-levels/) | A bank statement whose lines add up to 1000 and whose total says 1100 |
| 10 | Junior / mid | [Constraints and races](junior-mid/10-constraints-and-races/) | Two signups with the same email both succeed |
| 11 | Junior / mid | [Pagination](junior-mid/11-pagination/) | Page 5,000 reads 100,000 rows to return 20 |
| 12 | Junior / mid | [Caching with Redis](junior-mid/12-caching-with-redis/) | 20 requests for the same product, 20 calls to the slow source |
| 13 | Junior / mid | [Money as double](junior-mid/13-money-as-double/) | 1,000 payments of 0.10 add up to 100.00 and 99.99 is paid out |
| 14 | Junior / mid | [Authorisation and JWT](junior-mid/14-authorisation-and-jwt/) | Merchant A reads merchant B's invoices by changing the id in the URL |
| 15 | Junior / mid | [equals and hashCode](junior-mid/15-equals-and-hashcode/) | An item goes into a set, its quantity changes, and the set can no longer find it |

The numbers are the suggested order. Each project stands on its own, so you can start anywhere.

Expand Down
6 changes: 5 additions & 1 deletion java/concepts/ci-projects.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@
{ "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 },
{ "path": "java/concepts/junior-mid/09-isolation-levels", "startPass": 22, "total": 31 },
{ "path": "java/concepts/junior-mid/10-constraints-and-races", "startPass": 19, "total": 35 },
{ "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 }
{ "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 },
{ "path": "java/concepts/junior-mid/12-caching-with-redis", "startPass": 13, "total": 28 },
{ "path": "java/concepts/junior-mid/13-money-as-double", "startPass": 9, "total": 34 },
{ "path": "java/concepts/junior-mid/14-authorisation-and-jwt", "startPass": 15, "total": 31 },
{ "path": "java/concepts/junior-mid/15-equals-and-hashcode", "startPass": 14, "total": 34 }
]
326 changes: 326 additions & 0 deletions java/concepts/junior-mid/12-caching-with-redis/INTERVIEW_TASKS.md

Large diffs are not rendered by default.

176 changes: 176 additions & 0 deletions java/concepts/junior-mid/12-caching-with-redis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Caching with Redis — @Cacheable, Stale Data and the Stampede

> **In `start/`, `./check` FAILS on purpose: 13 of 28 checks pass.** That is the exercise, not a
> broken checkout. Tasks 2, 4, 5, 6, 7 and 8 turn the other 15 green. Some checks of Tasks 4 and 8
> pass at the start only because nothing is cached yet: adding the cache in Task 2 turns them red.
> That is part of the lesson.

A shop's product page is slow: loading one product takes 200 ms, because it is an expensive query
or a call to another service. Every visitor pays for it, every time. Everybody's first answer is
"put a cache in front of it". This project lets you do exactly that with Spring and Redis, and then
watch the five things that go wrong next: a price that does not change after an update, a cache
that one endpoint silently skips, entries that live for ever, a hot key that expires and sends
every request to the slow source at once, and a Redis outage that takes the whole shop down.

It answers the interview questions students most often get wrong:

- "How does `@Cacheable` work? What is stored in Redis, under which key?"
- "You update a row and users still see the old value. Why, and how do you fix it?"
- "`@CacheEvict` or `@CachePut`?"
- "Why does `@Cacheable` do nothing when I call the method from the same class?"
- "What is a cache stampede, and does `sync = true` fix it?"
- "Redis goes down. Does your application go down with it?"

## Tech Stack

- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate), Spring Data Redis (Lettuce)
- **PostgreSQL 17** and **Redis 8** in Docker
- JUnit 5, AssertJ, Testcontainers

## What you need

- JDK 25
- Docker, running

You do not need `redis-cli` or `psql`: the tools below talk to Redis and Postgres from Java.

## Getting Started

Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see
`./demo` (same for `inspect` and `check`).

```bash
cd start
docker compose up -d # Postgres on port 5451, Redis on port 6390
./demo # 20 requests for the same product: how many reach the slow source?
./check # 13 of 28 pass: that is your starting point
```

The first run downloads Maven and the dependencies, so it takes a minute or two.

When you are finished: `docker compose down`.

## The three tools

### `./demo` — see what happens

Starts the real application, sends requests at it over HTTP and counts how many of them had to call
the slow source. Every run starts from a clean state: prices reset, Redis emptied. Ends with a
`RESULT` line.

```
./demo 20 requests for product 1, one after the other
./demo --scenario update read a product, change its price, read it again
./demo --scenario basket the basket page, which shows products 1, 2 and 3
./demo --scenario stampede a cached product expires and 20 requests arrive at once
./demo --scenario redis-down the application cannot reach Redis
./demo --requests 50 --delay-ms 500 more requests, a slower source
./demo --requests 1 --ttl 15 cache with a 15 second TTL (watch it with ./inspect --watch)
./demo --help
```

### `./inspect` — look inside Redis

Lists every key in Redis with its TTL and its value, byte for byte, then puts each product row from
Postgres next to its cached copy and says whether they agree (`same` or `STALE`). Also shows the
last price changes. `./inspect --watch` refreshes every second for a minute.

### `./check` — are the acceptance criteria met?

`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything.
`./mvnw verify` runs the same tests the usual Maven way.

The tests are the acceptance criteria. **Never edit, delete or disable a test.** They start the
application against a real Postgres and a real Redis (Testcontainers), call it over HTTP, and count
how many times the slow source was called. Concurrency is forced with latches, never left to luck,
and no test measures time.

## The code

```
start/src/main/java/com/amigoscode/caching/
├── cache/
│ └── CacheConfig.java switching caching on and configuring Redis. Tasks 2, 6, 7 and 8
├── product/
│ ├── ProductController.java GET /api/products/{id}, GET /api/products?ids=..., PUT .../price
│ ├── ProductService.java what gets cached and evicted. Tasks 2, 4, 5 and 7
│ ├── SlowProductSource.java the slow part: 200 ms, then a read from Postgres. Nothing to change
│ ├── ProductView.java what the API returns and what gets cached
│ └── JdbcPriceHistory.java writes down every price change, in the same transaction
└── demo/ the demo and inspect tools. Nothing to change here
```

The endpoints:

| Endpoint | What it is |
|---|---|
| `GET /api/products/{id}` | The product page |
| `GET /api/products?ids=1,2,3` | The basket page: several products, in the order asked for |
| `PUT /api/products/{id}/price` with `{"price": 79.00}` | A price change from the back office |

## Two ways to work

- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and
hints for each task. Use this if you want to work it out yourself.
- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same nine tasks, step by step, with the output you
should see and an explanation of why. Use this to learn the concept, or when you are stuck.

Both files use the same task numbers.

| Task | What you do | Checked by |
|---|---|---|
| 1 | See every request pay for the slow source | you answer questions |
| 2 | Cache products in Redis, as JSON | `./check 2` |
| 3 | Inspect the cache, and watch it go stale | you answer questions |
| 4 | Fix the stale price after an update | `./check 4` |
| 5 | Fix the cache that the basket skips (self-invocation) | `./check 5` |
| 6 | Give cached products a TTL | `./check 6` |
| 7 | Fix the cache stampede | `./check 7` |
| 8 | Keep the shop up when Redis is down | `./check 8` |
| 9 | Compare, and decide what to cache | you answer questions |

## Solution

`solution/` is the same project with every task done: `cd solution && ./check` prints 28 of 28.

To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`).

<details>
<summary>Spoiler: the problems and the fixes</summary>

**Caching (Task 2).** `@EnableCaching`, then `@Cacheable(cacheNames = "products", key = "#productId")`
on `findById`. Spring Boot sees Redis and builds a `RedisCacheManager`. Its default stores values
with Java serialization: `ProductView` must be `Serializable`, and Redis holds 447 unreadable bytes.
A `RedisCacheManagerBuilderCustomizer` gives the `products` cache a JSON serializer instead: 51
bytes, `{"id":1,"name":"Mechanical keyboard","price":89.00}`, under the key `products::1`.

**Stale data (Task 4).** `PUT` changes the database and nothing tells the cache. `@CacheEvict` on
`changePrice` removes the entry, and the cache advice runs outside the transaction, so it happens
after the commit. Evicting before the commit (`beforeInvocation = true`) lets a reader put the old
price straight back. `@CachePut` also works, with its own race between two writers.

**Self-invocation (Task 5).** The basket calls `this.findById(...)`. The call never leaves the
object, so it never goes through the Spring proxy, so `@Cacheable` does not run. The same trap as
`@Transactional` (see [`../01-transactional`](../01-transactional)). Fix: call `findById` from
another bean.

**TTL (Task 6).** Entries live for ever by default. `.entryTtl(...)` in the cache configuration,
from `catalogue.cache.products-ttl`. The TTL is also the safety net for every change that does not
go through your `PUT`.

**Stampede (Task 7).** `sync = true` is only a request to the cache. Spring Data Redis's default
cache writer does not lock, so all 20 requests still load. A locking cache writer takes a lock key
in Redis (`products~lock`), which works across instances, but it locks the whole cache, not one
key, and it must have a timeout.

**Redis down (Task 8).** Every cache read fails, so every request is a 500. A `CacheErrorHandler`
(`LoggingCacheErrorHandler`) logs the failure and treats it as a miss. The shop is slower, not down.

| | `@CacheEvict` | `@CachePut` |
|---|---|---|
| After an update | Removes the entry; the next read loads it | Writes the new value straight away |
| Next read | One slow load | Fast |
| Risk | A slow reader can put an old value back | Two concurrent writers can leave the older value |
| Use it when | Almost always: it is the safe default | The method returns exactly what a read would return, and reads right after a write matter |

</details>
Loading
Loading