Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 · Projects and Practice

Practice Exercises and Challenges

Eight hands-on Bun exercises with hints and solutions: routing, validation, token-bucket rate limiting, SQLite queries, streaming CSV, mock-based tests, a config loader and a capstone.

Reading is not the same as building. These exercises go from short to ambitious and cover the chapters of this course. Try each one first without peeking at the hint, then compare with the solution. The solutions that matter most are runnable on Node 24 in the editors below (the logic is the same in Bun); Bun-only API parts are shown read-only.

Bun is not available on this site. Wherever an exercise says "in Bun", write it in a file and run bun run file.ts or bun test on your own machine. The TryIt blocks are Node stand-ins for the pure logic.

Exercise 1: A route table

Write a Bun.serve routes object for a library API: GET /books returns all books, GET /books/:isbn returns one (404 if unknown), and POST /books adds one from a JSON body (400 for a missing title, 201 on success). Use a Map as storage.

Hint: start from the shape in routes and parameters. Keep each handler a function from Request to Response.

Exercise 2: A token-bucket rate limiter

A token bucket allows bursts but limits the average rate. It holds up to capacity tokens and refills at ratePerSec tokens per second. Each request takes one token; with none left the request is rejected. Write createLimiter({ capacity, ratePerSec, now }) returning take(key): true if allowed, else false. Inject now so that it can be tested without waiting.

Node.js Solution 2: token bucket

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Think about it: where would you call take? In fetch, with server.requestIP(req)?.address as the key, answering 429 with a Retry-After header. What breaks when you run two processes?

Exercise 3: SQL practice with bun:sqlite

Create a sales table (id, region, product, amount, sold_on). Insert at least eight rows in one transaction. Then answer with queries: total per region, the best product in each region, and the running total over time. Use parameters for every value that is not a constant.

Hint: GROUP BY, and a window function SUM(amount) OVER (ORDER BY sold_on). See bun:sqlite for transactions.

Node.js Solution 3: aggregates and a window function (node:sqlite)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 4: Stream a big CSV

Write a function that reads a huge CSV line by line (never the whole file) and returns the number of rows where the third column is greater than 100. In Bun, Bun.file(path).stream() gives chunks; the tricky part is that a line can be split across two chunks.

Node.js Solution 4: chunk-safe line splitting

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 5: Write tests first

For a function slugify(title) that turns " Hello, World! 2026 " into "hello-world-2026", write the bun:test file before the function: cases for spaces, punctuation, repeated separators, accents ("Café" becomes "cafe"), and empty input. Then implement it until the tests pass. Use test.each (basics).

Node.js Solution 5: implementation plus a table of cases

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 6: A typed config loader

Write loadConfig(env) returning { port, databasePath, logLevel }. PORT must be an integer 1-65535 (default 3000), DB_PATH is required in production, and LOG_LEVEL must be one of debug, info, warn, error. Collect all errors and throw them together. The pattern appears in the Docker lesson; write your own version and test it with a table of inputs.

Exercise 7: A graceful-shutdown test

Start a server on port 0 whose handler waits 200 ms. Send a request, call server.stop() while it is running, and assert that the response still arrives. Then assert that a new connection after stop() is refused. Review production hardening for the idea.

Exercise 8: Capstone, a pastebin

Combine everything: a POST /api/pastes endpoint that stores { text, language, expiresInMinutes } in SQLite, GET /p/:id returning the text, an expires_at column that is honored on read (return 410 Gone after expiry), a cleanup timer that deletes expired rows, a size limit of 100 KB, a rate limit from Exercise 2, tests with an in-memory database, a Dockerfile and graceful shutdown. When it works, compile it with bun build --compile and run the binary on another machine.

Checklist for a good result: every route validates input; every error is JSON with the right status; no SQL by string concatenation; a test for each status code; a README with run instructions.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why inject a now() function into the rate limiter?

    An injectable clock makes time-dependent logic deterministic.
  2. 2. When streaming a file in chunks, why keep a rest buffer?

    Lines are not aligned with chunks, so carry the partial line over.
  3. 3. In SQL, what does RANK() OVER (PARTITION BY region ORDER BY SUM(amount) DESC) give you?

    PARTITION BY restarts the ranking for each region; filtering rank 1 gives the best product.
  4. 4. What status code should an expired paste return?

    410 says the resource existed and is permanently gone.

Summary

  • Practice by writing small pure functions (limiters, slugifiers, loaders), then wire them into routes.
  • Inject clocks and dependencies; test with tables of cases.
  • Stream large inputs and handle chunk boundaries.
  • Aggregates and window functions in SQLite go a long way before you need another database.
  • A capstone that combines API, storage, tests, limits, shutdown and packaging is the best proof you can ship with Bun.

Back to the track: Bun