URL Shortener
project: url shortener build a url shortener like bit.ly — encode long urls to short codes, redirect on access, track click counts.
Introduction
Build a URL shortener like bit.ly — encode long URLs to short codes, redirect on access, track click counts. Practice hashing/base62 encoding, Redis caching, rate limiting and high-read API design.
Informative example
Shorten and redirect:
@PostMapping("/shorten")public ShortUrlResponse shorten(@Valid @RequestBody ShortenRequest req) {String code = encoder.encode(urlRepo.save(req.url()).getId());cache.put(code, req.url()); // Redisreturn new ShortUrlResponse("https://short.io/" + code);}@GetMapping("/{code}")public ResponseEntity<Void> redirect(@PathVariable String code) {String url = cache.get(code).orElseGet(() -> urlRepo.findByCode(code));analytics.recordClick(code);return ResponseEntity.status(302).location(URI.create(url)).build();}
Best practices
- Use base62 (a-zA-Z0-9) for short codes — 6 chars = 56 billion URLs.
- Cache hot URLs in Redis — redirects are read-heavy.
- Add rate limiting (Resilience4j) on the shorten endpoint.
Purpose of this lesson
Master URL Shortener so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind URL Shortener.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when url shortener is the right tool for the problem.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Redis cache for hot redirect codes — 99% of traffic is reads.
- Base62 encoding keeps URLs short and URL-safe.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply URL Shortener daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain URL Shortener in one minute.
Q2When would you avoid URL Shortener?
Summary
In this lesson you learned URL Shortener — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.