<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rahul Verma on Medium]]></title>
        <description><![CDATA[Stories by Rahul Verma on Medium]]></description>
        <link>https://medium.com/@rahul281191?source=rss-bbaf34695b86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DlhRO7j_yH4bCBT0Vz1hXA.jpeg</url>
            <title>Stories by Rahul Verma on Medium</title>
            <link>https://medium.com/@rahul281191?source=rss-bbaf34695b86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul281191/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 6: Spring Security, From Attacks to JWT to OAuth2]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-6-spring-security-from-attacks-to-jwt-to-oauth2-ff64a24b6800?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff64a24b6800</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 06:13:37 GMT</pubDate>
            <atom:updated>2026-09-01T06:13:37.510Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 (final part) of a 6-part series. We’ve built a validated REST API (Parts 1–3), backed by a well-modeled database (Part 4), and made it production-ready with logging, auditing, and monitoring (Part 5). The one thing standing between this and a real application anyone can use safely: security. Let’s finish strong.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5OR_F_mZNiJcYvRk2h-eA.png" /></figure><p>Every endpoint we’ve built so far is wide open — anyone who knows the URL can create, read, update, or delete any user’s data. This final part fixes that properly: we’ll cover the attacks Spring Security defends against by default, exactly how it works internally, and then build a complete JWT authentication system with refresh tokens, Google OAuth2 login, and fine-grained role/permission-based access control.</p><p>This is the longest part of the series for a reason — security is where interviewers dig deepest, and where a shaky understanding causes the most real-world damage. Take your time here.</p><h4>Common Security Attacks: CSRF, XSS, and SQL Injection</h4><p>Before configuring anything, you need to understand what you’re actually defending against.</p><h4>SQL Injection</h4><p>This happens when user input is inserted directly into a SQL query as a raw string, letting an attacker manipulate the query itself.</p><pre>// NEVER do this:<br>String query = &quot;SELECT * FROM users WHERE email = &#39;&quot; + userInput + &quot;&#39;&quot;;</pre><p>If userInput is &#39; OR &#39;1&#39;=&#39;1, the query becomes:</p><pre>SELECT * FROM users WHERE email = &#39;&#39; OR &#39;1&#39;=&#39;1&#39;</pre><p>…which returns <em>every</em> row, bypassing the intended filter entirely. More dangerous injections can delete tables or extract unrelated data.</p><p><strong>Why Spring Data JPA protects you by default:</strong> every query derivation method (findByEmail, etc.) and every @Query with named parameters (:email) uses <strong>parameterized queries</strong> underneath — the user&#39;s input is sent to the database separately from the query structure, never concatenated into the SQL string itself. As long as you stick to Spring Data JPA&#39;s repository methods and parameterized @Query annotations (which we used exclusively throughout Part 4), you&#39;re safe from this by construction. The danger only reappears if you manually build native SQL strings with string concatenation — which you should simply never do.</p><h3>Cross-Site Scripting (XSS)</h3><blockquote>XSS happens when an attacker injects malicious JavaScript into content that gets rendered in another user’s browser — for example, submitting a comment containing in <em>script tag = steal(document.cookie)</em>, which then executes in the browser of anyone who views that comment.</blockquote><p>This is primarily a <strong>frontend rendering concern</strong> (modern frontend frameworks like React escape content by default, which is a major defense), but on the backend, Spring helps by:</p><ul><li>Encouraging JSON APIs (which we’ve built throughout this series) rather than server-rendered HTML — JSON data isn’t executed as a script by a browser the way HTML/JS content can be.</li><li>Allowing you to configure security headers like Content-Security-Policy, which restricts what kinds of scripts a browser is allowed to execute at all.</li></ul><h3>Cross-Site Request Forgery (CSRF)</h3><p>CSRF tricks a logged-in user’s browser into unknowingly sending a request to your app — for example, a malicious website embeds a hidden form that auto-submits POST /api/users/5/delete using the victim&#39;s existing browser session/cookies, without the victim ever intending to delete anything.</p><p>This attack specifically relies on <strong>cookie-based sessions</strong>, where the browser automatically attaches your session cookie to every request, including ones triggered by a different, malicious site. This is precisely why, later in this article, our stateless JWT-based API (where the token is sent explicitly in an Authorization header, not an automatic cookie) sidesteps this particular attack vector — there&#39;s no ambient session for a malicious site to piggyback on. Spring Security still ships with CSRF protection enabled by default, since it&#39;s designed to work for traditional session-based applications too; for our JWT-based API, we&#39;ll explicitly disable it, and explain exactly why that&#39;s the correct call in our case.</p><h3>Internal Working of Spring Security, Part 1: The Filter Chain</h3><p>Spring Security doesn’t work through Controllers, DTOs, or anything we’ve built so far. It works at a lower level, using <strong>Servlet Filters</strong> — a plain Java Servlet API concept that predates Spring entirely.</p><p>Recall from Part 2: Tomcat receives a raw HTTP request and hands it to the DispatcherServlet. What we didn’t mention then is that requests can pass through a <strong>chain of Filters</strong> <em>before</em> they ever reach the DispatcherServlet — each filter can inspect, modify, block, or pass along the request.</p><pre>Client Request<br>      │<br>      ▼<br>┌─────────────────────────────────────────┐<br>│         Spring Security Filter Chain      │<br>│  (a series of filters, each with one job) │<br>│                                            │<br>│  1. Filter: Check for CSRF token          │<br>│  2. Filter: Extract &amp; validate JWT        │<br>│  3. Filter: Load user details             │<br>│  4. Filter: Check authorization rules     │<br>│  ... and several more                     │<br>└─────────────────────────────────────────┘<br>      │<br>      ▼ (only if the request passes every filter)<br>DispatcherServlet → Controller → Service → Repository</pre><p>If any filter in this chain decides the request should be rejected (invalid token, insufficient permissions), it short-circuits immediately and sends back a 401 Unauthorized or 403 Forbidden — <strong>your Controller code never even runs.</strong> This is a crucial mental model: security decisions happen <em>before</em> your business logic, at the servlet level, completely separate from the MVC layer we spent Parts 2 and 3 building.</p><p>This is architecturally similar to Express middleware (app.use(authMiddleware)) running before your route handlers — except Spring Security&#39;s filter chain is far more structured, with dozens of specialized, ordered filters handling different concerns (authentication, authorization, CSRF, CORS, session management) rather than one custom function.</p><h3>Internal Working of Spring Security, Part 2: Core Components</h3><p>A handful of interfaces work together to make authentication happen. Understanding these makes every Spring Security configuration you’ll ever read make sense.</p><ul><li><strong>SecurityContextHolder</strong> — a static holder that gives access to the SecurityContext for the current thread. This is how, anywhere in your code, you can ask &quot;who is the currently authenticated user?&quot;</li><li><strong>SecurityContext</strong> — holds the current Authentication object.</li><li><strong>Authentication</strong> — represents the current user&#39;s authentication state: their identity (principal), credentials, and granted authorities (roles/permissions). Before login, this might not exist or be &quot;anonymous&quot;; after successful login, it holds the real user&#39;s details.</li><li><strong>UserDetailsService</strong> — an interface with one method, loadUserByUsername(String username), which you implement to tell Spring Security <em>how to fetch a user</em> from your own data source (in our case, via UserRepository).</li><li><strong>UserDetails</strong> — represents a user in a way Spring Security understands: username, password (hashed), and a collection of GrantedAuthority objects (their roles/permissions).</li><li><strong>AuthenticationProvider</strong> — does the actual work of verifying credentials (e.g., comparing a submitted password against the stored hash).</li><li><strong>AuthenticationManager</strong> — the entry point that delegates to the right AuthenticationProvider to actually attempt authentication.</li><li><strong>GrantedAuthority</strong> — represents a single permission or role granted to a user (e.g., &quot;ROLE_ADMIN&quot;).</li></ul><p>Here’s our UserDetailsService implementation, connecting Spring Security to the User entity and UserRepository we built back in Part 2 and Part 4:</p><pre>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br><br>    private final UserRepository userRepository;<br><br>    public CustomUserDetailsService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    @Override<br>    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {<br>        User user = userRepository.findByEmail(email)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;No user found with email: &quot; + email));<br><br>        return org.springframework.security.core.userdetails.User.builder()<br>                .username(user.getEmail())<br>                .password(user.getPassword())<br>                .authorities(user.getRoles().stream()<br>                        .map(role -&gt; new SimpleGrantedAuthority(&quot;ROLE_&quot; + role.getName()))<br>                        .toList())<br>                .build();<br>    }<br>}</pre><p>This is another example of everything from earlier parts converging — UserRepository (Part 4), the User and Role entities and their @ManyToMany relationship (Part 4), and Streams (Part 3) all feed directly into how Spring Security identifies and authorizes a user.</p><h3>SecurityFilterChain Configuration</h3><p>Modern Spring Security (version 6+, which ships with current Spring Boot versions) configures everything through a SecurityFilterChain Bean, using a fluent builder API on HttpSecurity:</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    private final JwtAuthFilter jwtAuthFilter; // we&#39;ll build this shortly<br>    private final CustomUserDetailsService userDetailsService;<br><br>    public SecurityConfig(JwtAuthFilter jwtAuthFilter, CustomUserDetailsService userDetailsService) {<br>        this.jwtAuthFilter = jwtAuthFilter;<br>        this.userDetailsService = userDetailsService;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .csrf(csrf -&gt; csrf.disable()) // safe to disable: we&#39;re stateless, no cookies involved<br>            .sessionManagement(session -&gt;<br>                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // no server-side sessions<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;).permitAll()      // signup/login are public<br>                .requestMatchers(&quot;/swagger-ui/**&quot;, &quot;/v3/api-docs/**&quot;).permitAll()<br>                .requestMatchers(&quot;/actuator/health&quot;).permitAll()<br>                .anyRequest().authenticated()                     // everything else needs a valid token<br>            )<br>            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br><br>    @Bean<br>    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {<br>        return config.getAuthenticationManager();<br>    }<br>}</pre><p>Key decisions explained:</p><ul><li><strong>csrf(csrf -&gt; csrf.disable())</strong> — safe here specifically <em>because</em> we&#39;re building a stateless, token-based API (no cookies, no ambient browser-managed session), which is immune to the CSRF attack described earlier. If you were building a traditional session/cookie-based app, you&#39;d keep CSRF protection enabled.</li><li><strong>SessionCreationPolicy.STATELESS</strong> — tells Spring Security never to create or use an HttpSession. Every request must prove who it is independently, via the JWT sent in its Authorization header — nothing is remembered between requests server-side.</li><li><strong>.requestMatchers(...).permitAll()</strong> — explicitly public endpoints (signup, login, API docs, health checks).</li><li><strong>.anyRequest().authenticated()</strong> — the default-deny rule: everything not explicitly listed above requires a valid, authenticated request.</li><li><strong>addFilterBefore(jwtAuthFilter, ...)</strong> — this is where our custom JWT filter (built below) gets slotted into the filter chain described earlier, running <em>before</em> Spring&#39;s default username/password filter.</li></ul><h3>Understanding JWT: Creation and Verification</h3><p>A <strong>JWT (JSON Web Token)</strong> is a compact, self-contained way to represent a user’s identity and claims, digitally signed so it can’t be tampered with. It has three parts, separated by dots: header.payload.signature.</p><pre>eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyYWh1bEBleGFtcGxlLmNvbSIsImlhdCI6MTcwMDAwMDAwMH0.4f8s...<br>└──────── header ────────┘└──────────── payload ────────────┘└── signature ──┘</pre><ul><li><strong>Header</strong> — metadata, like which signing algorithm was used (e.g., HS256).</li><li><strong>Payload</strong> — the actual claims: who the user is (sub), when the token was issued (iat), when it expires (exp), and any custom data you want to include (roles, user ID).</li><li><strong>Signature</strong> — generated by signing the header + payload using a secret key known only to your server. This is what makes the token tamper-proof: if anyone modifies the payload (say, changing their own role to “ADMIN”), the signature won’t match anymore, and your server will reject it.</li></ul><p><strong>Critically: JWT payloads are Base64-encoded, not encrypted.</strong> Anyone can decode and read a JWT’s contents — never put sensitive data (passwords, secrets) in the payload. The signature guarantees the content hasn’t been <em>tampered with</em>; it doesn’t hide the content.</p><p>Using the popular jjwt library, here&#39;s how to create and verify tokens:</p><pre>@Component<br>public class JwtService {<br><br>    @Value(&quot;${jwt.secret}&quot;)<br>    private String secretKey; // stored in application.properties / environment variables, never hardcoded<br><br>    @Value(&quot;${jwt.expiration-ms}&quot;)<br>    private long expirationMs;<br><br>    public String generateToken(String email, List&lt;String&gt; roles) {<br>        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));<br><br>        return Jwts.builder()<br>                .subject(email)<br>                .claim(&quot;roles&quot;, roles)<br>                .issuedAt(new Date())<br>                .expiration(new Date(System.currentTimeMillis() + expirationMs))<br>                .signWith(key)<br>                .compact();<br>    }<br><br>    public String extractEmail(String token) {<br>        return parseClaims(token).getSubject();<br>    }<br><br>    public boolean isTokenValid(String token, UserDetails userDetails) {<br>        String email = extractEmail(token);<br>        return email.equals(userDetails.getUsername()) &amp;&amp; !isTokenExpired(token);<br>    }<br><br>    private boolean isTokenExpired(String token) {<br>        return parseClaims(token).getExpiration().before(new Date());<br>    }<br><br>    private Claims parseClaims(String token) {<br>        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));<br>        return Jwts.parser().verifyWith(key).build()<br>                .parseSignedClaims(token).getPayload();<br>    }<br>}</pre><h3>Sign Up and Login Using JWT</h3><p><strong>Never store plain-text passwords.</strong> The BCryptPasswordEncoder Bean we defined in SecurityConfig hashes passwords using the bcrypt algorithm — a one-way hash specifically designed to be slow (resistant to brute-force attacks) and salted (resistant to precomputed &quot;rainbow table&quot; attacks).</p><pre>public record SignupRequest(@NotBlank String name, @NotBlank @Email String email, @NotBlank @Size(min = 8) String password) {}<br>public record LoginRequest(@NotBlank @Email String email, @NotBlank String password) {}<br>public record AuthResponse(String accessToken, String refreshToken) {}</pre><pre>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>public class AuthController {<br><br>    private final UserRepository userRepository;<br>    private final PasswordEncoder passwordEncoder;<br>    private final AuthenticationManager authenticationManager;<br>    private final JwtService jwtService;<br>    private final RefreshTokenService refreshTokenService; // covered in the next section<br><br>    // constructor omitted for brevity — same pattern as every Service/Controller so far<br><br>    @PostMapping(&quot;/signup&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; signup(@Valid @RequestBody SignupRequest request) {<br>        if (userRepository.findByEmail(request.email()).isPresent()) {<br>            throw new IllegalStateException(&quot;Email already registered&quot;);<br>        }<br><br>        User user = new User();<br>        user.setName(request.name());<br>        user.setEmail(request.email());<br>        user.setPassword(passwordEncoder.encode(request.password())); // hash before saving!<br>        userRepository.save(user);<br><br>        String accessToken = jwtService.generateToken(user.getEmail(), List.of(&quot;USER&quot;));<br>        String refreshToken = refreshTokenService.createRefreshToken(user);<br>        return ResponseEntity.status(HttpStatus.CREATED).body(new AuthResponse(accessToken, refreshToken));<br>    }<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; login(@Valid @RequestBody LoginRequest request) {<br>        // this line does the actual password verification, throwing BadCredentialsException on failure<br>        authenticationManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(request.email(), request.password())<br>        );<br><br>        User user = userRepository.findByEmail(request.email()).orElseThrow();<br>        List&lt;String&gt; roles = user.getRoles().stream().map(Role::getName).toList();<br><br>        String accessToken = jwtService.generateToken(user.getEmail(), roles);<br>        String refreshToken = refreshTokenService.createRefreshToken(user);<br>        return ResponseEntity.ok(new AuthResponse(accessToken, refreshToken));<br>    }<br>}</pre><p>Notice authenticationManager.authenticate(...) — this single line is where the AuthenticationManager → AuthenticationProvider → UserDetailsService chain from earlier actually runs: it loads the user by email, compares the submitted password against the stored bcrypt hash (using the PasswordEncoder Bean automatically), and throws BadCredentialsException if they don&#39;t match.</p><h3>Authenticating Requests Using JWT</h3><p>Now we build the custom filter referenced in SecurityConfig — it runs on <em>every</em> incoming request, extracts the JWT from the Authorization header, validates it, and tells Spring Security who&#39;s making the request.</p><pre>@Component<br>public class JwtAuthFilter extends OncePerRequestFilter {<br><br>    private final JwtService jwtService;<br>    private final CustomUserDetailsService userDetailsService;<br><br>    // constructor omitted for brevity<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,<br>                                     FilterChain filterChain) throws ServletException, IOException {<br><br>        String authHeader = request.getHeader(&quot;Authorization&quot;);<br><br>        if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>            filterChain.doFilter(request, response); // no token — let it pass through;<br>            return;                                   // anyRequest().authenticated() will reject it downstream if needed<br>        }<br><br>        String token = authHeader.substring(7); // strip &quot;Bearer &quot;<br>        String email = jwtService.extractEmail(token);<br><br>        if (email != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>            UserDetails userDetails = userDetailsService.loadUserByUsername(email);<br><br>            if (jwtService.isTokenValid(token, userDetails)) {<br>                UsernamePasswordAuthenticationToken authToken =<br>                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>                SecurityContextHolder.getContext().setAuthentication(authToken); // mark this request as authenticated<br>            }<br>        }<br><br>        filterChain.doFilter(request, response); // continue to the next filter / eventually the Controller<br>    }<br>}</pre><p>OncePerRequestFilter guarantees this logic runs exactly once per request, regardless of internal servlet forwarding. The critical line is SecurityContextHolder.getContext().setAuthentication(authToken) — once this is set, the rest of Spring Security (and your own code, anywhere, via SecurityContextHolder.getContext().getAuthentication()) considers this request authenticated as that specific user, for the remainder of its processing.</p><h3>Spring Security Exception Handling</h3><p>By default, Spring Security’s rejection responses are generic and don’t follow the consistent error format we built in Part 3’s @RestControllerAdvice. We fix this with two dedicated handlers:</p><pre>@Component<br>public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {<br>    @Override<br>    public void commence(HttpServletRequest request, HttpServletResponse response,<br>                          AuthenticationException authException) throws IOException {<br>        response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 401 — not authenticated at all<br>        response.setContentType(&quot;application/json&quot;);<br>        response.getWriter().write(<br>            &quot;{\&quot;status\&quot;: 401, \&quot;message\&quot;: \&quot;Authentication required or token is invalid\&quot;}&quot;<br>        );<br>    }<br>}</pre><pre>@Component<br>public class JwtAccessDeniedHandler implements AccessDeniedHandler {<br>    @Override<br>    public void handle(HttpServletRequest request, HttpServletResponse response,<br>                        AccessDeniedException accessDeniedException) throws IOException {<br>        response.setStatus(HttpStatus.FORBIDDEN.value()); // 403 — authenticated, but not authorized<br>        response.setContentType(&quot;application/json&quot;);<br>        response.getWriter().write(<br>            &quot;{\&quot;status\&quot;: 403, \&quot;message\&quot;: \&quot;You don&#39;t have permission to perform this action\&quot;}&quot;<br>        );<br>    }<br>}</pre><p>Wire them into SecurityConfig:</p><pre>.exceptionHandling(ex -&gt; ex<br>    .authenticationEntryPoint(jwtAuthenticationEntryPoint)  // handles 401s<br>    .accessDeniedHandler(jwtAccessDeniedHandler))            // handles 403s</pre><p>The distinction matters: <strong>401 Unauthorized</strong> means “I don’t know who you are” (missing or invalid token); <strong>403 Forbidden</strong> means “I know exactly who you are, and you’re not allowed to do this.” Mixing these up is a very common mistake, and one interviewers often probe for directly.</p><h3>Refresh Tokens and Access Token-Based Authentication</h3><p>Access tokens should be <strong>short-lived</strong> (typically 15 minutes to 1 hour) — if one is stolen, the damage window is small. But forcing users to log in every 15 minutes is a terrible experience. The solution is a <strong>refresh token</strong>: a separate, longer-lived token (days or weeks) used <em>only</em> to obtain a new access token, never sent with regular API requests.</p><pre>@Entity<br>public class RefreshToken {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(unique = true, nullable = false)<br>    private String token;<br><br>    @ManyToOne<br>    private User user;<br><br>    private Instant expiresAt;<br>}</pre><pre>@Service<br>public class RefreshTokenService {<br><br>    private final RefreshTokenRepository refreshTokenRepository;<br><br>    public String createRefreshToken(User user) {<br>        RefreshToken refreshToken = new RefreshToken();<br>        refreshToken.setUser(user);<br>        refreshToken.setToken(UUID.randomUUID().toString());<br>        refreshToken.setExpiresAt(Instant.now().plus(7, ChronoUnit.DAYS));<br>        refreshTokenRepository.save(refreshToken);<br>        return refreshToken.getToken();<br>    }<br><br>    public RefreshToken verifyAndGet(String token) {<br>        RefreshToken refreshToken = refreshTokenRepository.findByToken(token)<br>                .orElseThrow(() -&gt; new IllegalArgumentException(&quot;Invalid refresh token&quot;));<br><br>        if (refreshToken.getExpiresAt().isBefore(Instant.now())) {<br>            refreshTokenRepository.delete(refreshToken);<br>            throw new IllegalStateException(&quot;Refresh token expired, please log in again&quot;);<br>        }<br>        return refreshToken;<br>    }<br>}</pre><pre>@PostMapping(&quot;/refresh&quot;)<br>public ResponseEntity&lt;AuthResponse&gt; refresh(@RequestBody Map&lt;String, String&gt; body) {<br>    RefreshToken refreshToken = refreshTokenService.verifyAndGet(body.get(&quot;refreshToken&quot;));<br>    User user = refreshToken.getUser();<br><br>    List&lt;String&gt; roles = user.getRoles().stream().map(Role::getName).toList();<br>    String newAccessToken = jwtService.generateToken(user.getEmail(), roles);<br><br>    return ResponseEntity.ok(new AuthResponse(newAccessToken, refreshToken.getToken()));<br>}</pre><p>Storing refresh tokens in the database (rather than just trusting a longer-lived JWT) is deliberate — unlike a stateless JWT, a database-backed refresh token can be <strong>revoked</strong> at any time (e.g., on logout, or if a device is reported stolen), simply by deleting its row. This is a common, practical compromise between JWT’s statelessness and the real-world need to invalidate sessions.</p><h3>Google OAuth2 Client Authentication</h3><p>Instead of (or alongside) email/password login, you can let users sign in with an existing Google account. Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-oauth2-client&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Configure your Google OAuth2 credentials (obtained from the Google Cloud Console) in application.properties:</p><pre>spring.security.oauth2.client.registration.google.client-id=${GOOGLE_CLIENT_ID}<br>spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_CLIENT_SECRET}<br>spring.security.oauth2.client.registration.google.scope=openid,profile,email</pre><p>And enable OAuth2 login in SecurityConfig:</p><pre>.oauth2Login(oauth2 -&gt; oauth2<br>    .successHandler((request, response, authentication) -&gt; {<br>        OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();<br>        String email = oAuth2User.getAttribute(&quot;email&quot;);<br>        String name = oAuth2User.getAttribute(&quot;name&quot;);<br><br>        // find or create a local User record, then issue our own JWT — same as regular login<br>        User user = userRepository.findByEmail(email)<br>                .orElseGet(() -&gt; userRepository.save(new User(name, email)));<br><br>        String accessToken = jwtService.generateToken(user.getEmail(), List.of(&quot;USER&quot;));<br>        response.sendRedirect(&quot;https://your-frontend.com/oauth-callback?token=&quot; + accessToken);<br>    })<br>)</pre><p>The flow: your app redirects the user to Google’s login page → Google authenticates them and redirects back to your app with an authorization code → Spring Security automatically exchanges that code for the user’s profile info → your successHandler runs, where you link that Google identity to your own User table and issue your own JWT, exactly like a normal login. From that point forward, your frontend treats it identically to email/password auth — same access token, same refresh token flow, same JwtAuthFilter validating every request.</p><h3>User Session Management with JWT</h3><p>Since JWTs are stateless by design, “logging out” isn’t as simple as clearing a server-side session — a valid JWT remains technically valid until it expires, even after a user clicks “log out,” unless you take deliberate steps. Common approaches, often combined:</p><ul><li><strong>Short-lived access tokens</strong> (15–30 minutes) mean any leaked or “logged out” token naturally becomes useless soon anyway.</li><li><strong>Refresh token revocation</strong> — since we store refresh tokens in the database (as built above), “logout” simply deletes that user’s refresh token row. They can’t get a new access token, and their current one expires shortly after.</li><li><strong>Token blacklisting</strong> for access tokens, if you need immediate invalidation (e.g., a compromised account) — typically implemented with a fast, in-memory store like Redis, storing revoked token IDs until their natural expiry, and checking against that blacklist in JwtAuthFilter.</li><li><strong>Tracking active sessions per user</strong> — storing metadata (device, IP, last active time) alongside each refresh token, letting you build a “log out of all devices” feature or show users their active sessions, similar to what most banking or email apps offer.</li></ul><h3>Role-Based Authorization</h3><p>Authentication answers “who are you?” — <strong>authorization</strong> answers “what are you allowed to do?” We touched on roles earlier (GrantedAuthority, &quot;ROLE_&quot; + role.getName()); here&#39;s how to actually enforce them.</p><p><strong>At the URL level, in </strong><strong>SecurityConfig:</strong></p><pre>.authorizeHttpRequests(auth -&gt; auth<br>    .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>    .requestMatchers(&quot;/api/admin/**&quot;).hasRole(&quot;ADMIN&quot;)<br>    .requestMatchers(HttpMethod.DELETE, &quot;/api/users/**&quot;).hasRole(&quot;ADMIN&quot;)<br>    .anyRequest().authenticated()<br>)</pre><p>Note: hasRole(&quot;ADMIN&quot;) automatically expects the authority to be named &quot;ROLE_ADMIN&quot; — Spring Security adds the ROLE_ prefix convention for you, which is why our CustomUserDetailsService explicitly built authorities as &quot;ROLE_&quot; + role.getName() earlier.</p><h3>Granular Authorization with Authorities and Permissions</h3><p>Roles are coarse (“ADMIN” can do everything admin-related). Real applications often need finer control — for example, “editors can edit posts, but only senior editors can delete them,” independent of a simple role hierarchy. This is where <strong>authorities/permissions</strong> come in — the same underlying mechanism as roles, but representing specific actions rather than broad job titles.</p><pre>.requestMatchers(HttpMethod.DELETE, &quot;/api/users/**&quot;).hasAuthority(&quot;user:delete&quot;)<br>.requestMatchers(HttpMethod.PATCH, &quot;/api/users/**&quot;).hasAnyAuthority(&quot;user:edit&quot;, &quot;user:edit:own&quot;)</pre><p>In practice, you’d model this with a Permission entity, similar to Role, and assign specific permissions to specific roles (or directly to users, for exceptions) — giving you a flexible permission system rather than hardcoded role names sprinkled throughout your security config. hasRole(&quot;ADMIN&quot;) is really just a convenience shortcut on top of the exact same GrantedAuthority mechanism used for fine-grained permissions.</p><h3>Security Method Annotations: @Secured and @PreAuthorize</h3><p>So far, our authorization rules lived entirely in SecurityConfig, tied to URL patterns. Sometimes it&#39;s clearer to put authorization rules directly on the Service or Controller method they protect. First, enable method security:</p><pre>@Configuration<br>@EnableMethodSecurity<br>public class SecurityConfig {<br>    // ... existing config<br>}</pre><p><strong>@Secured</strong> — simple, role-based only:</p><pre>@Secured(&quot;ROLE_ADMIN&quot;)<br>public void deleteUser(Long id) {<br>    userRepository.deleteById(id);<br>}</pre><p><strong>@PreAuthorize</strong> — far more powerful, supporting full Spring Expression Language (SpEL), including checks against method arguments:</p><pre>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>public void deleteUser(Long id) {<br>    userRepository.deleteById(id);<br>}<br><br>// Only allow users to edit their OWN profile, unless they&#39;re an admin<br>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;) or #id == authentication.principal.id&quot;)<br>public User updateUser(Long id, UserRequestDTO request) {<br>    // ...<br>}<br><br>@PreAuthorize(&quot;hasAuthority(&#39;user:delete&#39;)&quot;)<br>public void deleteUserGranular(Long id) {<br>    userRepository.deleteById(id);<br>}</pre><p>@PreAuthorize runs <em>before</em> the method executes (hence &quot;pre&quot;), throwing AccessDeniedException — which flows straight into the JwtAccessDeniedHandler we built earlier — if the expression evaluates to false. In modern Spring Security, @PreAuthorize is generally preferred over @Secured precisely because of this flexibility to reference method parameters and the current authenticated principal directly in the expression.</p><h3>Series Wrap-Up: What You’ve Built</h3><p>Across six parts, you went from “why does Spring even need all these annotations” to a genuinely complete, production-shaped full-stack backend:</p><ul><li><strong>Part 1</strong> — <em>why</em> Spring exists: solving tight coupling, testability, and object-creation sprawl through Beans and Dependency Injection.</li><li><strong>Part 2</strong> — a working REST API, understanding exactly how a request travels from Tomcat through the DispatcherServlet into your Controller, Service, and Repository layers.</li><li><strong>Part 3</strong> — validated, well-structured endpoints with centralized error handling and a solid grip on Java 8’s Lambdas and Streams.</li><li><strong>Part 4</strong> — a properly modeled relational database, understanding JPA/Hibernate internals deeply enough to model relationships correctly and avoid the N+1 query trap.</li><li><strong>Part 5</strong> — the operational maturity to actually run this in production: auditing, logging, health checks, and self-documenting APIs.</li><li><strong>Part 6</strong> — a real authentication and authorization system: JWT access/refresh tokens, Google OAuth2, and both role-based and fine-grained permission-based access control.</li></ul><p>That’s the complete backend skill set most full-stack and backend job descriptions are actually asking for, built as one coherent, connected application rather than six disconnected topics. From here, natural next steps include: writing automated tests (unit tests with Mockito, integration tests with @SpringBootTest and Testcontainers), containerizing this application with Docker, and connecting it to a real frontend — but that grounding you now have in <em>why</em> each piece exists, not just how to configure it, is what will make all of that click quickly.</p><p><em>This is Part 6, the final part, of the “Spring Boot for Full-Stack Developers” series. Thank you for following along from Spring fundamentals all the way to a fully secured, production-ready application.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff64a24b6800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 5: Making Your App Production-Ready (DevTools…]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-5-making-your-app-production-ready-devtools-bf1c8ea3acec?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf1c8ea3acec</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 06:11:24 GMT</pubDate>
            <atom:updated>2026-08-30T06:11:24.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Full-Stack Developers — Part 5: Making Your App Production-Ready (DevTools, Auditing, Logging, Actuator, and API Docs)</h3><p><em>Part 5 of a 6-part series. So far we’ve built a validated, well-structured REST API (Parts 1–3) backed by a properly modeled database (Part 4). Now we add the things that separate a “working” application from a “production-ready” one — the stuff that matters once real users, real teammates, and real incidents get involved.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwVZf101xm_ZsfeFZQhuKA.png" /></figure><p>Everything we’ve built so far would technically work if you deployed it. But ask yourself: if this API crashed at 2 AM, would you know why? If a support ticket says “my data got changed and I don’t know when or by whom,” could you find out? If a frontend developer on your team asked “what does this endpoint actually expect,” would you have anything to show them besides your source code?</p><p>This part is about closing those gaps.</p><h3>A Quick Recap: Project Setup</h3><p>Back in Part 2, we set up our project with spring-boot-starter-web and spring-boot-starter-data-jpa — Spring Boot Web MVC for handling HTTP, and Spring Data JPA for persistence, both of which we&#39;ve been building on ever since. Everything in this part adds new dependencies on top of that same foundation — nothing here requires starting a new project.</p><h3>Spring Boot DevTools</h3><p>spring-boot-devtools is a small dependency that makes local development noticeably faster and more convenient. Add it to your pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>    &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><p>What it gives you:</p><ul><li><strong>Automatic restart</strong> — whenever you change a Java file and recompile (most IDEs do this automatically on save), Spring Boot detects the change and restarts your application automatically. It’s smart about it too — it uses two classloaders internally, so only <em>your</em> code gets reloaded, not third-party libraries, which makes restarts much faster than a full cold start.</li><li><strong>LiveReload</strong> — DevTools runs a small LiveReload server that can auto-refresh your browser when static resources change, useful if you’re serving any frontend assets directly from Spring Boot.</li><li><strong>Sensible dev-only defaults</strong> — for example, disabling template caching, so you see changes immediately instead of getting a cached version.</li></ul><p>The optional=true and scope=runtime settings ensure DevTools never gets bundled into your final production build — this is purely a local development convenience tool. If you&#39;ve used nodemon to auto-restart a Node.js server on file changes, this is doing the same job for a Java project, and it&#39;s genuinely one of those small quality-of-life additions you’ll wonder how you lived without.</p><h3>Auditing: Knowing Who Changed What, and When</h3><h4>Basic Auditing</h4><p>For most applications, you want to know, at minimum, when a record was created and when it was last modified. Spring Data JPA provides this almost for free.</p><p><strong>Step 1: Create a base class for common audit fields.</strong></p><pre>@MappedSuperclass<br>@EntityListeners(AuditingEntityListener.class)<br>public abstract class Auditable {<br><br>    @CreatedDate<br>    @Column(updatable = false)<br>    private LocalDateTime createdAt;<br><br>    @LastModifiedDate<br>    private LocalDateTime updatedAt;<br><br>    @CreatedBy<br>    @Column(updatable = false)<br>    private String createdBy;<br><br>    @LastModifiedBy<br>    private String updatedBy;<br><br>    // getters (no setters needed — these are managed automatically)<br>}</pre><ul><li>@MappedSuperclass means this isn&#39;t its own database table — its fields just get merged into any entity that extends it.</li><li>@EntityListeners(AuditingEntityListener.class) hooks into JPA lifecycle events (remember the Entity Lifecycle from Part 4?) to automatically populate these fields on save/update.</li></ul><p><strong>Step 2: Extend it in your entities.</strong></p><pre>@Entity<br>public class User extends Auditable {<br>    // ... existing fields from previous parts<br>}</pre><p>Step 3: Enable JPA auditing in your main application class (or a @Configuration class).</p><pre>@SpringBootApplication<br>@EnableJpaAuditing<br>public class MyApp {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApp.class, args);<br>    }<br>}</pre><p>Step 4 (for @CreatedBy/@LastModifiedBy): tell Spring how to determine the current user.</p><pre>@Component<br>public class SpringSecurityAuditorAware implements AuditorAware&lt;String&gt; {<br>    @Override<br>    public Optional&lt;String&gt; getCurrentAuditor() {<br>        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>        if (authentication == null || !authentication.isAuthenticated()) {<br>            return Optional.of(&quot;system&quot;);<br>        }<br>        return Optional.of(authentication.getName());<br>    }<br>}</pre><p>We haven’t covered Spring Security yet (that’s all of Part 6), but this snippet shows the shape of it — once we add real authentication, this class pulls the currently logged-in user’s identity automatically, and every entity extending Auditable will record exactly who created or last touched each record, with zero extra code in your Service layer.</p><h3>Advanced Auditing with Hibernate Envers</h3><p>Basic auditing tells you the <em>current</em> state’s created/updated timestamps — but it doesn’t answer “what did this record look like <em>last Tuesday</em>, before it was changed three times?” For full historical tracking, Spring integrates with <strong>Hibernate Envers</strong>.</p><p>Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt;<br>    &lt;artifactId&gt;hibernate-envers&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Mark any entity you want full history for:</p><pre>@Entity<br>@Audited<br>public class User extends Auditable {<br>    // ... existing fields<br>}</pre><p>That single @Audited annotation tells Hibernate to automatically create a <strong>shadow &quot;history&quot; table</strong> (named users_aud by default) — and every time a User row is inserted, updated, or deleted, Envers writes a full snapshot of that row into the history table, tagged with a revision number and timestamp.</p><p>To actually query this history:</p><pre>@Autowired<br>private EntityManager entityManager;<br><br>public List&lt;User&gt; getUserHistory(Long userId) {<br>    AuditReader auditReader = AuditReaderFactory.get(entityManager);<br>    List&lt;Number&gt; revisions = auditReader.getRevisions(User.class, userId);<br><br>    return revisions.stream()<br>            .map(revision -&gt; auditReader.find(User.class, userId, revision))<br>            .toList();<br>}</pre><p>This gives you a complete, queryable timeline of every version a specific User record has ever had — genuinely valuable for compliance-heavy applications (finance, healthcare) or just for debugging &quot;how did this data end up wrong&quot; support tickets months after the fact.</p><h3>Making Third-Party API Calls with RestClient</h3><p>Real-world backends rarely operate in isolation — you’ll often need to call external services: a payment gateway, a geocoding API, another internal microservice. Spring’s modern tool for this is RestClient (introduced in Spring Framework 6.1, and the recommended replacement for the older RestTemplate).</p><pre>@Service<br>public class WeatherService {<br><br>    private final RestClient restClient;<br><br>    public WeatherService(RestClient.Builder restClientBuilder) {<br>        this.restClient = restClientBuilder<br>                .baseUrl(&quot;https://api.example-weather.com&quot;)<br>                .build();<br>    }<br><br>    public WeatherResponse getWeather(String city) {<br>        return restClient.get()<br>                .uri(&quot;/v1/weather?city={city}&quot;, city)<br>                .retrieve()<br>                .body(WeatherResponse.class);<br>    }<br><br>    public void reportIncident(IncidentRequest request) {<br>        restClient.post()<br>                .uri(&quot;/v1/incidents&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .body(request)<br>                .retrieve()<br>                .toBodilessEntity();<br>    }<br>}</pre><ul><li>RestClient.Builder is itself a Bean, auto-configured by Spring Boot — you inject it, then use .build() to create a client configured for a specific base URL.</li><li>.get() / .post() / .put() / .delete() mirror the HTTP methods, similar to how you&#39;d use axios.get() or fetch() in a Node.js/frontend project.</li><li>.retrieve().body(SomeClass.class) automatically deserializes the JSON response into a Java object, exactly like the @RequestBody deserialization we saw in Part 2 — same underlying JSON conversion machinery.</li></ul><p>For proper error handling on non-2xx responses:</p><pre>public WeatherResponse getWeather(String city) {<br>    return restClient.get()<br>            .uri(&quot;/v1/weather?city={city}&quot;, city)<br>            .retrieve()<br>            .onStatus(HttpStatusCode::is4xxClientError, (request, response) -&gt; {<br>                throw new IllegalArgumentException(&quot;Invalid city: &quot; + city);<br>            })<br>            .onStatus(HttpStatusCode::is5xxServerError, (request, response) -&gt; {<br>                throw new ExternalServiceException(&quot;Weather service is currently unavailable&quot;);<br>            })<br>            .body(WeatherResponse.class);<br>}</pre><p>Note that these custom exceptions (ExternalServiceException, etc.) would flow straight into the global @RestControllerAdvice handler we built in Part 3 — the same centralized error-handling pattern applies just as well to failures from external services, not just your own business logic.</p><h3>Logging in Spring Boot Applications</h3><p>You might be tempted to debug with System.out.println(...) — resist that urge in any real application. Spring Boot comes preconfigured with <strong>SLF4J</strong> (a logging facade/interface) backed by <strong>Logback</strong> (the actual logging implementation) — this pairing is the Java equivalent of using a proper logging library (like winston or pino) instead of scattering console.log everywhere in a Node.js app.</p><pre>@Service<br>public class UserService {<br><br>    private static final Logger log = LoggerFactory.getLogger(UserService.class);<br><br>    public User createUser(String name, String email) {<br>        log.info(&quot;Creating user with email: {}&quot;, email);<br><br>        if (userRepository.findByEmail(email).isPresent()) {<br>            log.warn(&quot;Attempted to create user with duplicate email: {}&quot;, email);<br>            throw new IllegalStateException(&quot;Email already registered&quot;);<br>        }<br><br>        User user = userRepository.save(new User(name, email));<br>        log.info(&quot;User created successfully with id: {}&quot;, user.getId());<br>        return user;<br>    }<br>}</pre><p>Notice {} used as a placeholder instead of string concatenation (&quot;Creating user: &quot; + email) — this is more efficient, since the string is only actually built if that log level is enabled, and it&#39;s the idiomatic SLF4J style you&#39;ll see everywhere.</p><p><strong>Log levels</strong>, from most to least verbose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*7AZB4CD4kNJ4YcyR7E2CMQ.png" /></figure><p>You control which levels actually get printed via application.properties:</p><pre>logging.level.root=INFO<br>logging.level.com.example.myapp=DEBUG<br>logging.level.org.hibernate.SQL=DEBUG</pre><p>That last line, incidentally, is a more controlled alternative to the spring.jpa.show-sql=true we used in Part 4 — it routes Hibernate&#39;s SQL logging through the same logging framework as everything else, so it respects log levels and formatting consistently instead of just printing raw SQL to stdout.</p><p>If you’re using <strong>Lombok</strong> (a popular library that reduces boilerplate like getters/setters), you can skip the manual Logger declaration entirely with @Slf4j:</p><pre>@Slf4j<br>@Service<br>public class UserService {<br>    public User createUser(String name, String email) {<br>        log.info(&quot;Creating user with email: {}&quot;, email);<br>        // ...<br>    }<br>}</pre><h3>Spring Boot Actuator</h3><p><strong>Actuator</strong> exposes a set of production-monitoring endpoints for your running application, with almost zero setup. Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>By default, this exposes a /actuator/health endpoint returning:</p><pre>{ &quot;status&quot;: &quot;UP&quot; }</pre><p>This single endpoint is exactly what tools like Kubernetes, load balancers, and uptime monitors use for <strong>liveness and readiness probes</strong> — automated systems that repeatedly check “is this service alive and able to handle traffic?” and take action (like restarting a crashed pod) if it isn’t.</p><p>Other useful Actuator endpoints (most need to be explicitly enabled, since exposing everything by default is a security risk):</p><pre>management.endpoints.web.exposure.include=health,info,metrics,env<br>management.endpoint.health.show-details=always</pre><ul><li><strong>/actuator/info</strong> — custom application metadata (version, build info) you configure yourself.</li><li><strong>/actuator/metrics</strong> — runtime metrics: memory usage, active HTTP requests, database connection pool stats, garbage collection activity, and more.</li><li><strong>/actuator/env</strong> — currently active configuration properties and environment variables (be careful exposing this in production — it can leak sensitive config).</li></ul><p>A more detailed /actuator/health response, once you&#39;ve added a database connection, will even report the health of your database connectivity specifically:</p><pre>{<br>  &quot;status&quot;: &quot;UP&quot;,<br>  &quot;components&quot;: {<br>    &quot;db&quot;: { &quot;status&quot;: &quot;UP&quot;, &quot;details&quot;: { &quot;database&quot;: &quot;MySQL&quot; } },<br>    &quot;diskSpace&quot;: { &quot;status&quot;: &quot;UP&quot; }<br>  }<br>}</pre><p><strong>Important security note:</strong> Actuator endpoints can expose sensitive internal details. In any real deployment, you should restrict which endpoints are exposed publicly and secure the sensitive ones (like /env and /metrics) behind authentication — we&#39;ll cover exactly how to do that with Spring Security in Part 6.</p><h3>OpenAPI and Swagger for API Documentation</h3><p>Once your API grows beyond a handful of endpoints, keeping documentation in sync manually becomes unrealistic. <strong>springdoc-openapi</strong> solves this by generating interactive API documentation directly from your existing Controller code and annotations — no separate doc-writing process required.</p><p>Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>    &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>    &lt;version&gt;2.5.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>That’s it — run your application, and visit http://localhost:8080/swagger-ui.html. You&#39;ll get a fully interactive UI listing every endpoint, their expected request bodies, response shapes, and even a &quot;Try it out&quot; button to fire real requests directly from the browser. It reads all of this by inspecting your @RestController classes, your DTOs, and the annotations we&#39;ve used throughout this series (@GetMapping, @RequestBody, validation annotations, etc.) automatically.</p><p>You can enrich the generated docs with additional annotations for clarity:</p><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>@Tag(name = &quot;User Management&quot;, description = &quot;Endpoints for managing users&quot;)<br>public class UserController {<br><br>    @Operation(summary = &quot;Create a new user&quot;, description = &quot;Registers a new user with a name and email&quot;)<br>    @ApiResponse(responseCode = &quot;201&quot;, description = &quot;User created successfully&quot;)<br>    @ApiResponse(responseCode = &quot;400&quot;, description = &quot;Validation failed&quot;)<br>    @PostMapping<br>    public ResponseEntity&lt;UserResponseDTO&gt; createUser(@Valid @RequestBody UserRequestDTO request) {<br>        // ... unchanged from Part 3<br>    }<br>}</pre><pre>public class UserRequestDTO {<br><br>    @Schema(description = &quot;Full name of the user&quot;, example = &quot;Rahul Verma&quot;)<br>    @NotBlank<br>    private String name;<br><br>    @Schema(description = &quot;Unique email address&quot;, example = &quot;rahul@example.com&quot;)<br>    @NotBlank<br>    @Email<br>    private String email;<br>}</pre><p>This is directly comparable to using swagger-jsdoc or @nestjs/swagger in a Node.js project — but because Spring already knows the shape of your DTOs and validation rules through annotations you&#39;ve already written for other purposes, the generated documentation tends to require far less duplicate effort to keep accurate. For any team working with a separate frontend (React, Angular, mobile), this Swagger UI becomes the single source of truth both sides can reference — exactly the kind of artifact that saves you from a dozen &quot;wait, does this field return null or an empty string?&quot; Slack messages.</p><h3>What We Covered</h3><ul><li><strong>Spring Boot DevTools</strong> speeds up local development with automatic restarts and live reload — never shipped to production.</li><li><strong>Basic auditing</strong> (@CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy) tracks who changed a record and when, with almost no code.</li><li><strong>Hibernate Envers</strong> (@Audited) goes further, maintaining a full historical revision log of every change to an entity, queryable at any point in time.</li><li><strong>RestClient</strong> is Spring&#39;s modern tool for calling external APIs, with built-in JSON conversion and structured error handling that plugs into the exception handling pattern from Part 3.</li><li>Proper <strong>logging</strong> (SLF4J + Logback, with appropriate log levels) replaces System.out.println and gives you real visibility into what your application is doing.</li><li><strong>Spring Boot Actuator</strong> exposes health checks and runtime metrics that monitoring tools and orchestration platforms (like Kubernetes) rely on.</li><li><strong>springdoc-openapi (Swagger)</strong> auto-generates interactive, always-accurate API documentation directly from your existing code and annotations.</li></ul><p><em>(For homework, try wiring </em><em>Auditable into every entity from Part 4, add Envers to your </em><em>User entity, and expose your full API through Swagger UI — you should be able to explore and test your entire API from the browser without writing a single test request by hand.)</em></p><p>In <strong>Part 6</strong>, the final part of this series, we tackle <strong>Spring Security</strong> end to end: understanding attacks like CSRF, XSS, and SQL Injection; how Spring Security actually works internally; building a full JWT-based authentication system with refresh tokens; adding Google OAuth2 login; and implementing role-based and fine-grained permission-based authorization.</p><p><em>This is Part 5 of a 6-part “Spring Boot for Full-Stack Developers” series. Parts 1–4 covered Spring fundamentals, REST API basics, validation/exceptions, and Spring Data JPA.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1c8ea3acec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 4: Spring Data JPA, Hibernate, and Mastering…]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-4-spring-data-jpa-hibernate-and-mastering-cd52df6112e0?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd52df6112e0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[javadatabase]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 05:31:01 GMT</pubDate>
            <atom:updated>2026-08-21T05:31:01.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Full-Stack Developers — Part 4: Spring Data JPA, Hibernate, and Mastering Relationships</h3><p><em>Part 4 of a 6-part series. So far we’ve covered Spring fundamentals (Part 1), building a REST API (Part 2), and validation/exception handling (Part 3). Now we go deep into how Spring Boot actually talks to a database — this is the part most Java job interviews spend the most time on, so take it slow.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYwx8F-_g5ltwMBI8lEvAA.png" /></figure><p>We’ve been using UserRepository extends JpaRepository&lt;User, Long&gt; since Part 2 without fully explaining what&#39;s happening underneath it. It&#39;s time to open that box. This part covers the tooling, the theory (JPA vs Hibernate), the practical day-to-day (queries, sorting, pagination, projections), and the trickiest topic in this whole series: relationships between entities, and the performance traps that come with them.</p><h3>Installing PostgreSQL and DBeaver</h3><p>Until now, you could use an in-memory database like H2 for learning. For anything resembling a real application, you’ll want a proper relational database — <strong>PostgreSQL</strong> is one of the most widely used, free, open-source options, and it’s a safe default to learn on.</p><p><strong>Installing PostgreSQL:</strong></p><ul><li><strong>Windows/Mac:</strong> Download the installer from the official PostgreSQL site (postgresql.org) and follow the setup wizard — it will ask you to set a password for the default postgres superuser. Remember it; you&#39;ll need it constantly.</li><li><strong>Mac (via Homebrew):</strong> brew install postgresql@16, then brew services start postgresql@16.</li><li><strong>Linux:</strong> Install via your package manager, e.g., sudo apt install postgresql, then sudo systemctl start postgresql.</li></ul><p>Once installed, PostgreSQL runs as a background service listening on port 5432 by default. You&#39;ll connect to it from Spring Boot using a JDBC URL that looks like:</p><pre>jdbc:postgresql://localhost:5432/user_management_db</pre><p><strong>Installing DBeaver:</strong></p><p>DBeaver is a free, universal database GUI client — think of it as a visual tool for browsing tables, running SQL queries, and inspecting data, without typing everything into a terminal. Download it from dbeaver.io, install it, then create a new PostgreSQL connection using localhost, port 5432, and the postgres user credentials you set up during installation. Once connected, you can browse your database visually — see tables, columns, and run ad-hoc SQL — which is invaluable for debugging what Hibernate is actually doing to your data (more on this shortly).</p><p>In your Spring Boot project’s application.properties, you&#39;d configure the connection like this:</p><pre>spring.datasource.url=jdbc:postgresql://localhost:5432/user_management_db<br>spring.datasource.username=postgres<br>spring.datasource.password=your_password<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true</pre><p>spring.jpa.hibernate.ddl-auto=update tells Hibernate to automatically create/update your database tables based on your @Entity classes — extremely convenient while learning, though in real production systems, teams usually manage schema changes more carefully using migration tools like Flyway or Liquibase instead of relying on this setting. spring.jpa.show-sql=true prints every SQL statement Hibernate generates to your console — turn this on while learning; it&#39;s the single best way to understand what&#39;s actually happening behind your annotations.</p><h3>Hibernate, JPA, Entities, and Tables — Clearing Up the Confusion</h3><p>This trips up almost everyone at first, so let’s be precise:</p><ul><li><strong>JPA (Jakarta Persistence API)</strong> is a <em>specification</em> — a set of interfaces and rules describing how Java objects should map to database tables. It’s not code you can run by itself; it’s a contract.</li><li><strong>Hibernate</strong> is the most popular <em>implementation</em> of that contract — the actual code that does the work of translating your Java objects into SQL and back.</li><li><strong>Spring Data JPA</strong> is a layer on top of both, built by the Spring team, that eliminates even more boilerplate (like the JpaRepository interface we&#39;ve used since Part 2).</li></ul><p>The relationship looks like this:</p><pre>Spring Data JPA  (Spring&#39;s convenience layer — repositories, query derivation)<br>        │<br>        ▼<br>      JPA         (the specification/interface — javax.persistence / jakarta.persistence)<br>        │<br>        ▼<br>    Hibernate     (the actual implementation that talks to the database)</pre><p>In Node.js, Sequelize plays a similar role to Hibernate — it sits on top of the raw PostgreSQL driver, and turns your model code into SQL for you. But there’s one key difference. Hibernate follows a shared rulebook called JPA, and other tools (like EclipseLink) follow that same rulebook too. That’s why you could swap Hibernate for one of those other tools without changing your @Entity classes at all. Sequelize doesn&#39;t have this. There&#39;s no separate rulebook behind Sequelize — its own API is the only rulebook. So there&#39;s no other library you could swap in without rewriting your model code.</p><p><strong>Object-Relational Mapping (ORM)</strong> is the general concept behind all of this: converting between two fundamentally different ways of representing data — Java objects (with fields, references, inheritance) and relational database tables (with rows, columns, foreign keys). This translation is exactly what an @Entity class describes:</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(name = &quot;full_name&quot;, nullable = false, length = 100)<br>    private String name;<br><br>    @Column(unique = true, nullable = false)<br>    private String email;<br><br>    private LocalDateTime createdAt;<br>}</pre><ul><li>@Entity — this class maps to a database table.</li><li>@Table(name = &quot;users&quot;) — optional; if omitted, Hibernate uses the class name as the table name. Use it when you want the table name to differ from the class name.</li><li>@Column — customizes how a field maps to a column: its name, whether it&#39;s nullable, its length, uniqueness, and more. If omitted, Hibernate infers a column with the same name as the field.</li><li>@Id and @GeneratedValue — as covered in Part 2, marks the primary key and how it&#39;s generated (IDENTITY means &quot;let the database auto-increment it&quot; — PostgreSQL implements this internally as an auto-incrementing identity column, the modern equivalent of the older SERIAL type).</li></ul><h3>Spring Data JPA Interfaces and Dynamic Query Methods</h3><p>Spring Data JPA gives you a hierarchy of repository interfaces, each adding more capability:</p><pre>Repository&lt;T, ID&gt;                  — marker interface, base of everything<br>     │<br>     ▼<br>CrudRepository&lt;T, ID&gt;              — adds save(), findById(), findAll(), deleteById(), etc.<br>     │<br>     ▼<br>PagingAndSortingRepository&lt;T, ID&gt;  — adds paginated and sorted queries<br>     │<br>     ▼<br>JpaRepository&lt;T, ID&gt;               — adds JPA-specific extras (batch operations, flushing, etc.)</pre><p>In practice, you almost always extend JpaRepository&lt;T, ID&gt; directly, since it includes everything below it in the hierarchy.</p><h3>Dynamic Query Methods (Query Derivation)</h3><p>This is one of Spring Data JPA’s most useful features: <strong>you can define a query just by naming a method a certain way</strong>, and Spring generates the actual SQL for you — no implementation, no annotations required.</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br><br>    Optional&lt;User&gt; findByEmail(String email);<br><br>    List&lt;User&gt; findByNameContainingIgnoreCase(String namePart);<br><br>    List&lt;User&gt; findByCreatedAtAfter(LocalDateTime date);<br><br>    List&lt;User&gt; findByNameAndEmail(String name, String email);<br><br>    boolean existsByEmail(String email);<br><br>    long countByCreatedAtAfter(LocalDateTime date);<br><br>    void deleteByEmail(String email);<br>}</pre><p>Spring parses the method name itself: findByNameContainingIgnoreCase translates to &quot;find records where the name column contains this substring, case-insensitively&quot; — and generates:</p><pre>SELECT * FROM users WHERE LOWER(name) LIKE LOWER(CONCAT(&#39;%&#39;, ?, &#39;%&#39;))</pre><p>Common keywords you can combine in method names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*mShjk72GFUbdywiK9QC9vA.png" /></figure><h4>When Method Names Aren’t Enough: @Query</h4><p>For more complex queries, write JPQL (Java Persistence Query Language — SQL-like, but operates on entity/field names instead of table/column names) directly:</p><pre>@Query(&quot;SELECT u FROM User u WHERE u.email LIKE %:domain%&quot;)<br>List&lt;User&gt; findByEmailDomain(@Param(&quot;domain&quot;) String domain);</pre><p>Or, if you need raw SQL for something JPQL can’t express well:</p><pre>@Query(value = &quot;SELECT * FROM users WHERE created_at &gt; NOW() - INTERVAL &#39;7 days&#39;&quot;, nativeQuery = true)<br>List&lt;User&gt; findRecentUsers();</pre><p>This is the Spring equivalent of writing raw SQL strings with a query builder in Node — except query derivation means you often don’t need to write SQL at all for straightforward lookups.</p><h3>Sorting and Pagination</h3><p>Fetching <em>all</em> rows from a large table is rarely a good idea. Spring Data JPA has built-in support for sorting and pagination using two special parameter types: Sort and Pageable.</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    Page&lt;User&gt; findByNameContainingIgnoreCase(String namePart, Pageable pageable);<br>}</pre><pre>@GetMapping<br>public ResponseEntity&lt;Page&lt;UserResponseDTO&gt;&gt; getAllUsers(<br>        @RequestParam(defaultValue = &quot;0&quot;) int page,<br>        @RequestParam(defaultValue = &quot;10&quot;) int size,<br>        @RequestParam(defaultValue = &quot;name&quot;) String sortBy) {<br><br>    Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy).ascending());<br>    Page&lt;User&gt; userPage = userRepository.findAll(pageable);<br>    Page&lt;UserResponseDTO&gt; response = userPage.map(this::toResponseDTO);<br>    return ResponseEntity.ok(response);<br>}</pre><p>A request like GET /api/users?page=0&amp;size=10&amp;sortBy=name returns not just the 10 users, but a Page&lt;T&gt; object containing rich metadata:</p><pre>{<br>  &quot;content&quot;: [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;Aisha&quot; }, &quot;...9 more&quot; ],<br>  &quot;totalElements&quot;: 47,<br>  &quot;totalPages&quot;: 5,<br>  &quot;number&quot;: 0,<br>  &quot;size&quot;: 10,<br>  &quot;first&quot;: true,<br>  &quot;last&quot;: false<br>}</pre><p>Behind the scenes, Hibernate generates SQL with LIMIT and OFFSET clauses, and runs a separate COUNT(*) query to calculate totalElements. This is the standard, production-ready way to handle large lists — never load an entire table into memory and paginate manually in Java.</p><h3>Projections in Spring Data JPA</h3><p>Sometimes you don’t need the <em>entire</em> entity — just a couple of fields. Fetching the full User object (and all its relationships, more on that soon) when you only need name and email is wasteful. <strong>Projections</strong> let you fetch only what you need, directly at the query level.</p><p><strong>Interface-based projection:</strong></p><pre>public interface UserNameEmailView {<br>    String getName();<br>    String getEmail();<br>}</pre><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    List&lt;UserNameEmailView&gt; findByCreatedAtAfter(LocalDateTime date);<br>}</pre><p>Spring Data JPA automatically implements this interface at runtime and, importantly, generates a SQL query that <strong>only selects the </strong><strong>name and </strong><strong>email columns</strong> — not the whole row.</p><p><strong>Class-based (DTO) projection</strong>, which some teams prefer since it’s more explicit and works well with constructors:</p><pre>public class UserSummaryDTO {<br>    private final String name;<br>    private final String email;<br><br>    public UserSummaryDTO(String name, String email) {<br>        this.name = name;<br>        this.email = email;<br>    }<br>    // getters<br>}</pre><pre>@Query(&quot;SELECT new com.example.dto.UserSummaryDTO(u.name, u.email) FROM User u&quot;)<br>List&lt;UserSummaryDTO&gt; findAllSummaries();</pre><p>Projections are a genuinely important performance tool once your entities have several relationships attached (as we’re about to build) — fetching a full User entity might trigger loading related Order and Address records you don&#39;t even need for a given screen.</p><h3>Hibernate Entity Lifecycle, EntityManager, and Persistence Context</h3><p>This is more conceptual, but it explains <em>why</em> certain things “just work” in JPA — like calling user.setName(&quot;New Name&quot;) on an entity you fetched, and having that change automatically saved without ever calling .save() again.</p><p>Every entity object, at any point in time, is in one of <strong>four states</strong>:</p><ol><li><strong>Transient</strong> — a plain Java object, just created with new User(), not yet associated with the database or tracked by JPA at all.</li><li><strong>Managed</strong> — the entity is tracked by the current <strong>Persistence Context</strong>. Any changes you make to its fields will automatically be detected and saved when the transaction commits (called “dirty checking”).</li><li><strong>Detached</strong> — the entity <em>was</em> managed, but the persistence context that tracked it has since closed (e.g., the transaction ended). Changes to a detached entity are no longer automatically tracked.</li><li><strong>Removed</strong> — the entity has been marked for deletion; it will be removed from the database when the transaction commits.</li></ol><p>The <strong>EntityManager</strong> is the core JPA interface responsible for managing this — creating, reading, updating, and deleting entities, and tracking their state. When you call userRepository.save(user), Spring Data JPA is calling the EntityManager underneath.</p><p>The <strong>Persistence Context</strong> is essentially a first-level cache and change-tracking system, scoped to a single transaction. This is why the following works without an explicit save() call:</p><pre>@Transactional<br>public void updateUserName(Long id, String newName) {<br>    User user = userRepository.findById(id).orElseThrow();<br>    user.setName(newName); // no .save() called here!<br>    // when this method finishes and the transaction commits,<br>    // Hibernate compares the entity&#39;s current state to what it originally loaded,<br>    // notices the &quot;name&quot; field changed, and automatically issues an UPDATE statement<br>}</pre><p>This “automatic save on change” behavior <strong>only</strong> happens while the entity is <em>managed</em> — i.e., inside an active persistence context, which is exactly what @Transactional (covered next) provides.</p><h3>Relationships: OneToOne, OneToMany, ManyToOne, ManyToMany</h3><p>This is where most of the real complexity in JPA lives. Let’s extend our User Management domain with two related concepts: each User has one Address, and each User can place many Orders.</p><h4>@OneToOne</h4><pre>@Entity<br>public class Address {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String street;<br>    private String city;<br><br>    @OneToOne<br>    @JoinColumn(name = &quot;user_id&quot;) // this entity owns the foreign key<br>    private User user;<br>}</pre><pre>@Entity<br>public class User {<br>    // ...previous fields<br><br>    @OneToOne(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL)<br>    private Address address;<br>}</pre><p>The side with @JoinColumn is the <strong>owning side</strong> — it holds the actual foreign key column in its database table. The other side uses mappedBy to say &quot;I don&#39;t own this relationship; look at the user field on Address to understand it.&quot; This is purely about <em>which table</em> has the foreign key column — conceptually, the relationship is still bidirectional (you can navigate it from either object in Java).</p><h4>@ManyToOne and @OneToMany</h4><p>These are always two sides of the same relationship — “many” orders belong to “one” user.</p><pre>@Entity<br>public class Order {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private BigDecimal amount;<br><br>    @ManyToOne<br>    @JoinColumn(name = &quot;user_id&quot;) // the &quot;many&quot; side always owns the foreign key<br>    private User user;<br>}</pre><pre>@Entity<br>public class User {<br>    // ...previous fields<br><br>    @OneToMany(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL, orphanRemoval = true)<br>    private List&lt;Order&gt; orders = new ArrayList&lt;&gt;();<br>}</pre><p><strong>Rule of thumb:</strong> the @ManyToOne side is almost always the owning side (it holds the foreign key), and @OneToMany almost always uses mappedBy to point back to it. This mirrors how the actual SQL table structure works — the orders table has a user_id column, not the other way around.</p><h4>@ManyToMany</h4><p>For a scenario like “a user can have many roles, and a role can belong to many users”:</p><pre>@Entity<br>public class User {<br>    // ...previous fields<br><br>    @ManyToMany<br>    @JoinTable(<br>        name = &quot;user_roles&quot;,<br>        joinColumns = @JoinColumn(name = &quot;user_id&quot;),<br>        inverseJoinColumns = @JoinColumn(name = &quot;role_id&quot;)<br>    )<br>    private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();<br>}</pre><pre>@Entity<br>public class Role {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name; // e.g. &quot;ADMIN&quot;, &quot;USER&quot;<br><br>    @ManyToMany(mappedBy = &quot;roles&quot;)<br>    private Set&lt;User&gt; users = new HashSet&lt;&gt;();<br>}</pre><p>@JoinTable tells Hibernate to create a separate join table (user_roles) with two foreign key columns — this is the standard way relational databases represent many-to-many relationships, since neither table can directly hold a &quot;list&quot; of foreign keys.</p><h3>Cascading Types and @Transactional</h3><h4>Cascading</h4><p><strong>Cascading</strong> controls whether an operation on the parent entity should automatically apply to its related child entities. Without cascading, saving a User with a new Address attached wouldn&#39;t automatically save that Address — you&#39;d have to save it separately.</p><pre>@OneToOne(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL)<br>private Address address;</pre><p>Common cascade types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*P_6XlJhAkkqcSu9epJVoeQ.png" /></figure><p>Use CascadeType.ALL carefully — it&#39;s convenient, but it also means deleting a User will delete their Address and all their Orders. For relationships where the child entity has meaning independent of the parent (imagine a Product that many Orders reference), you&#39;d generally avoid cascading REMOVE.</p><h4>@Transactional</h4><p>A <strong>transaction</strong> groups multiple database operations into a single all-or-nothing unit — if any part fails, everything rolls back, leaving the database exactly as it was before.</p><pre>@Service<br>public class UserService {<br><br>    @Transactional<br>    public User createUserWithAddress(String name, String email, String street, String city) {<br>        User user = new User();<br>        user.setName(name);<br>        user.setEmail(email);<br><br>        Address address = new Address();<br>        address.setStreet(street);<br>        address.setCity(city);<br>        address.setUser(user);<br>        user.setAddress(address);<br><br>        return userRepository.save(user); // saves both User AND Address, thanks to cascading<br>    }<br>}</pre><p>If an exception occurs anywhere inside a @Transactional method, Spring automatically rolls back everything that happened during that method — no partial saves, no half-created users without addresses. This is the same <strong>ACID</strong> guarantee (specifically, Atomicity) you&#39;d expect from any relational database transaction, and it&#39;s why @Transactional is almost always present on Service-layer methods that touch multiple entities or perform multi-step writes.</p><h3>FetchType, Orphan Removal, and the N+1 Query Problem</h3><h4>FetchType: EAGER vs LAZY</h4><p>Every relationship annotation has a fetch attribute controlling <em>when</em> related data actually gets loaded from the database:</p><ul><li><strong>FetchType.EAGER</strong> — related data is loaded immediately, in the same query (or a follow-up one) as the parent.</li><li><strong>FetchType.LAZY</strong> — related data is only loaded the <em>first time you actually access it</em> in code.</li></ul><pre>@OneToMany(mappedBy = &quot;user&quot;, fetch = FetchType.LAZY)<br>private List&lt;Order&gt; orders;</pre><p>Default fetch types in JPA: @ManyToOne and @OneToOne default to EAGER; @OneToMany and @ManyToMany default to LAZY. In practice, most experienced Spring developers explicitly set relationships to LAZY almost everywhere, and only fetch related data intentionally when it&#39;s actually needed — EAGER loading by default is a common source of unnecessary performance problems in real applications.</p><h4>Orphan Removal</h4><pre>@OneToMany(mappedBy = &quot;user&quot;, orphanRemoval = true)<br>private List&lt;Order&gt; orders;</pre><p>orphanRemoval = true means: if an Order is removed from the user.getOrders() list in Java (even without explicitly deleting it), Hibernate will detect it&#39;s no longer referenced by its parent and delete it from the database automatically. This is different from CascadeType.REMOVE, which only triggers when the <em>parent itself</em> is deleted — orphanRemoval also triggers when a child is simply detached from its parent&#39;s collection.</p><h4>The N+1 Query Problem</h4><p>This is one of the most common Spring Boot performance issues, and a favorite interview topic. Here’s how it happens:</p><pre>List&lt;User&gt; users = userRepository.findAll(); // 1 query: SELECT * FROM users<br><br>for (User user : users) {<br>    System.out.println(user.getOrders().size()); // triggers 1 query PER user, since orders is LAZY<br>}</pre><p>If you have 100 users, this runs <strong>1 query to fetch all users, plus 100 more queries</strong> — one for each user’s orders, fired individually the moment you access .getOrders() inside the loop. That&#39;s the &quot;N+1&quot; problem: 1 initial query, plus N additional queries (one per row).</p><p><strong>Solution 1: </strong><strong>JOIN FETCH in a custom query</strong>, which tells Hibernate to fetch the related data in the <em>same</em> query using a SQL join:</p><pre>@Query(&quot;SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.orders&quot;)<br>List&lt;User&gt; findAllWithOrders();</pre><p>This produces a single SQL query with a JOIN, loading users and their orders together in one round trip to the database.</p><p><strong>Solution 2: </strong><strong>@EntityGraph</strong>, a more declarative way to say &quot;when fetching this entity, also eagerly load these specific relationships, just for this query&quot;:</p><pre>@EntityGraph(attributePaths = {&quot;orders&quot;})<br>@Query(&quot;SELECT u FROM User u&quot;)<br>List&lt;User&gt; findAllWithOrdersGraph();</pre><p><strong>Solution 3: Batch fetching</strong>, configured globally or per-entity, which doesn’t eliminate the extra queries entirely but groups them — instead of 100 individual queries, Hibernate might run 10 queries, each fetching orders for a batch of 10 users at once:</p><pre>@OneToMany(mappedBy = &quot;user&quot;)<br>@BatchSize(size = 10)<br>private List&lt;Order&gt; orders;</pre><p>The key lesson: <strong>LAZY loading is usually the right default</strong>, but you need to be deliberate about <em>when</em> you actually need related data, and fetch it explicitly (via JOIN FETCH or @EntityGraph) rather than letting it trigger implicitly, one query at a time, inside a loop. Turning on spring.jpa.show-sql=true (from the setup section above) is exactly how you&#39;d catch this kind of problem during development — if you see dozens of near-identical SELECT statements in your console for what should be one screen of data, you&#39;ve found an N+1 problem.</p><h3>What We Covered</h3><ul><li><strong>JPA</strong> is a specification; <strong>Hibernate</strong> is its most common implementation; <strong>Spring Data JPA</strong> adds repository conveniences on top of both.</li><li><strong>Query derivation</strong> lets you define database queries just by naming repository methods correctly; @Query handles anything more complex.</li><li><strong>Pageable</strong> and <strong>Sort</strong> give you production-ready pagination and sorting with almost no code.</li><li><strong>Projections</strong> (interface-based or DTO-based) let you fetch only the fields you need, improving performance.</li><li>The <strong>Entity Lifecycle</strong> (Transient → Managed → Detached / Removed) and the <strong>Persistence Context</strong> explain why modifying a managed entity’s fields is enough to trigger an automatic UPDATE — no explicit .save() needed.</li><li>@OneToOne, @OneToMany/@ManyToOne, and @ManyToMany model relationships between entities; the side holding the foreign key is the &quot;owning side.&quot;</li><li><strong>Cascading</strong> controls whether operations on a parent propagate to its children; <strong>@Transactional</strong> ensures multi-step database operations are all-or-nothing.</li><li><strong>FetchType.LAZY</strong> should generally be your default, and the <strong>N+1 query problem</strong> — one of the most common real-world performance bugs — is solved with JOIN FETCH, @EntityGraph, or batch fetching.</li></ul><p><em>(Try the original course’s homework for this module on your own — build out the </em><em>Order and </em><em>Address entities above into a full working project, and use DBeaver to inspect the generated tables and foreign keys directly.)</em></p><p>In <strong>Part 5</strong>, we shift from “make it work” to “make it production-ready”: Spring Boot DevTools, auditing (including Hibernate Envers for full change history), calling third-party APIs with RestClient, structured logging, health checks with Spring Boot Actuator, and auto-generating API documentation with OpenAPI/Swagger.</p><p><em>This is Part 4 of a 6-part “Spring Boot for Full-Stack Developers” series. Parts 1–3 covered Spring fundamentals, building your first REST API, and validation/exception handling.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd52df6112e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 3: Validation, Exception Handling, and Java 8’s…]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-3-validation-exception-handling-and-java-8s-ce3ea01c72c6?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce3ea01c72c6</guid>
            <category><![CDATA[java-lambda-expression]]></category>
            <category><![CDATA[spring-validation]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java8-streams]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 07:11:01 GMT</pubDate>
            <atom:updated>2026-08-20T07:11:01.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Full-Stack Developers — Part 3: Validation, Exception Handling, and Java 8’s Lambda/Stream API</h3><p><em>Part 3 of a 6-part series. In Part 1 we covered Spring fundamentals (Beans, DI). In Part 2 we built our first REST API using the three-layer architecture. Now we’ll make that API production-quality: proper update/delete endpoints, real input validation, clean error handling, and the Java features that make Spring code so readable.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__9FP7DUSr7KNpoz5xaigA.png" /></figure><p>Right now, our User Management API from Part 2 can create, fetch, and list users — but it has some serious gaps. There’s no way to update or delete a user. If someone sends a request with a missing email or a malformed one, our app will either crash with a confusing error or silently save bad data. And if something <em>does</em> go wrong, the client gets an ugly Java stack trace instead of a clean error message.</p><p>Let’s fix all of that.</p><h3>PUT, PATCH, and DELETE Mappings</h3><p>You already know @GetMapping and @PostMapping from Part 2. Here&#39;s what the other three HTTP methods mean, and when to use each one.</p><ul><li><strong>PUT</strong> — replaces the <em>entire</em> resource. The client sends the full object; whatever fields aren’t included are treated as if they should be cleared or reset.</li><li><strong>PATCH</strong> — updates <em>part</em> of a resource. The client sends only the fields they want to change; everything else stays as-is.</li><li><strong>DELETE</strong> — removes the resource.</li></ul><h4>PUT — Full Update</h4><pre>@PutMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;UserResponseDTO&gt; updateUser(<br>        @PathVariable Long id,<br>        @RequestBody UserRequestDTO request) {<br><br>    User updatedUser = userService.updateUser(id, request.getName(), request.getEmail());<br>    return ResponseEntity.ok(toResponseDTO(updatedUser));<br>}</pre><pre>// in UserService<br>public User updateUser(Long id, String name, String email) {<br>    User user = userRepository.findById(id)<br>            .orElseThrow(() -&gt; new NoSuchElementException(&quot;User not found&quot;));<br>    user.setName(name);   // both fields are always overwritten —<br>    user.setEmail(email); // that&#39;s what makes this a PUT, not a PATCH<br>    return userRepository.save(user);<br>}</pre><h4>PATCH — Partial Update</h4><p>For PATCH, we only want to update fields that were actually provided. A clean way to express “this field may or may not be present” is to make the fields in the request DTO nullable and only apply the ones that aren’t null:</p><pre>public class UserPatchDTO {<br>    private String name;   // null = &quot;don&#39;t change this&quot;<br>    private String email;  // null = &quot;don&#39;t change this&quot;<br>    // getters and setters<br>}</pre><pre>@PatchMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;UserResponseDTO&gt; patchUser(<br>        @PathVariable Long id,<br>        @RequestBody UserPatchDTO request) {<br><br>    User updatedUser = userService.patchUser(id, request);<br>    return ResponseEntity.ok(toResponseDTO(updatedUser));<br>}</pre><pre>// in UserService<br>public User patchUser(Long id, UserPatchDTO request) {<br>    User user = userRepository.findById(id)<br>            .orElseThrow(() -&gt; new NoSuchElementException(&quot;User not found&quot;));<br><br>    if (request.getName() != null) {<br>        user.setName(request.getName());<br>    }<br>    if (request.getEmail() != null) {<br>        user.setEmail(request.getEmail());<br>    }<br>    return userRepository.save(user);<br>}</pre><p>DELETE</p><pre>@DeleteMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;Void&gt; deleteUser(@PathVariable Long id) {<br>    userService.deleteUser(id);<br>    return ResponseEntity.noContent().build(); // 204 No Content<br>}</pre><pre>// in UserService<br>public void deleteUser(Long id) {<br>    if (!userRepository.existsById(id)) {<br>        throw new NoSuchElementException(&quot;User not found&quot;);<br>    }<br>    userRepository.deleteById(id);<br>}</pre><p>Note ResponseEntity.noContent().build() — this returns HTTP status 204, which is the standard convention for &quot;the delete succeeded, and there&#39;s nothing meaningful to send back.&quot;</p><h3>Input Validation Annotations</h3><p>Right now, nothing stops a client from sending { &quot;name&quot;: &quot;&quot;, &quot;email&quot;: &quot;not-an-email&quot; }. We need <strong>validation</strong> — and Spring makes this almost declarative using the <strong>Bean Validation</strong> standard (also called Jakarta Validation, formerly known as JSR-380).</p><p>First, add the dependency (if not already included): spring-boot-starter-validation.</p><p>Then annotate your DTO fields directly:</p><pre>public class UserRequestDTO {<br><br>    @NotBlank(message = &quot;Name is required&quot;)<br>    @Size(min = 2, max = 50, message = &quot;Name must be between 2 and 50 characters&quot;)<br>    private String name;<br><br>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Email(message = &quot;Email must be a valid email address&quot;)<br>    private String email;<br><br>    // getters and setters<br>}</pre><p>Common validation annotations you’ll use constantly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*cQQfzQkgmpf_HIL94kN7Og.png" /></figure><p>To actually trigger this validation, you add @Valid in the Controller method:</p><pre>@PostMapping<br>public ResponseEntity&lt;UserResponseDTO&gt; createUser(@Valid @RequestBody UserRequestDTO request) {<br>    // if validation fails, this method body never even runs —<br>    // Spring throws a MethodArgumentNotValidException before it gets here<br>    User user = userService.createUser(request.getName(), request.getEmail());<br>    return ResponseEntity.status(HttpStatus.CREATED).body(toResponseDTO(user));<br>}</pre><p>If validation fails, Spring throws MethodArgumentNotValidException automatically — we&#39;ll catch this properly in the exception handling section below, instead of letting it crash into an ugly default error page.</p><p>If you’ve used a library like Zod or Joi in a Node.js/Express project, this should feel familiar — the difference is that in Spring, validation rules live as annotations directly on the DTO fields, rather than as a separate schema object.</p><h3>Creating a Custom Validation Annotation</h3><p>Sometimes the built-in annotations aren’t enough. Say we want to make sure a user’s email doesn’t already exist in the database <em>before</em> we try to save it, and we want this check reusable across the app. We can build our own annotation.</p><p><strong>Step 1: Define the annotation itself.</strong></p><pre>@Target({ ElementType.FIELD })<br>@Retention(RetentionPolicy.RUNTIME)<br>@Constraint(validatedBy = UniqueEmailValidator.class)<br>public @interface UniqueEmail {<br>    String message() default &quot;Email is already registered&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><p>Step 2: Write the validator logic that backs it.</p><pre>@Component<br>public class UniqueEmailValidator implements ConstraintValidator&lt;UniqueEmail, String&gt; {<br><br>    private final UserRepository userRepository;<br><br>    public UniqueEmailValidator(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    @Override<br>    public boolean isValid(String email, ConstraintValidatorContext context) {<br>        if (email == null) {<br>            return true; // let @NotBlank handle null/empty checks separately<br>        }<br>        return userRepository.findByEmail(email).isEmpty();<br>    }<br>}</pre><p>Step 3: Use it exactly like any built-in annotation.</p><pre>public class UserRequestDTO {<br><br>    @NotBlank<br>    private String name;<br><br>    @NotBlank<br>    @Email<br>    @UniqueEmail<br>    private String email;<br>}</pre><p>Notice that UniqueEmailValidator is annotated with @Component — meaning it&#39;s a Spring Bean, which means it can use <strong>Dependency Injection</strong> (from Part 1!) to get access to UserRepository and actually query the database as part of validation. This is a great example of how the concepts from earlier parts combine — Beans and DI aren&#39;t just abstract theory, they&#39;re what make features like this possible.</p><h3>Exception Handling in Spring Boot Web MVC</h3><p>Without any handling, an unexpected error (like the NoSuchElementException we throw when a user isn&#39;t found) results in Spring&#39;s default error response — a generic JSON blob with a stack trace-like structure that leaks internal details and isn&#39;t consistent across your API.</p><p>The fix is a <strong>global exception handler</strong>, using @RestControllerAdvice (a combination of @ControllerAdvice and @ResponseBody). This is one class that catches exceptions thrown <em>anywhere</em> in your Controllers and converts them into clean, consistent JSON responses.</p><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(NoSuchElementException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleNotFound(NoSuchElementException ex) {<br>        ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage());<br>        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);<br>    }<br><br>    @ExceptionHandler(IllegalStateException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleConflict(IllegalStateException ex) {<br>        ErrorResponse error = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage());<br>        return ResponseEntity.status(HttpStatus.CONFLICT).body(error);<br>    }<br><br>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleValidation(MethodArgumentNotValidException ex) {<br>        String message = ex.getBindingResult().getFieldErrors().stream()<br>                .map(error -&gt; error.getField() + &quot;: &quot; + error.getDefaultMessage())<br>                .collect(Collectors.joining(&quot;, &quot;));<br>        ErrorResponse error = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), message);<br>        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);<br>    }<br><br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleGeneric(Exception ex) {<br>        ErrorResponse error = new ErrorResponse(<br>                HttpStatus.INTERNAL_SERVER_ERROR.value(),<br>                &quot;Something went wrong. Please try again later.&quot;<br>        );<br>        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);<br>    }<br>}</pre><pre>public class ErrorResponse {<br>    private int status;<br>    private String message;<br>    private LocalDateTime timestamp = LocalDateTime.now();<br><br>    public ErrorResponse(int status, String message) {<br>        this.status = status;<br>        this.message = message;<br>    }<br>    // getters<br>}</pre><p>Now, no matter where in your app an exception is thrown, the client always gets a consistent shape back:</p><pre>{<br>  &quot;status&quot;: 404,<br>  &quot;message&quot;: &quot;User not found&quot;,<br>  &quot;timestamp&quot;: &quot;2026-08-12T10:15:30&quot;<br>}</pre><p>Notice the <strong>handleGeneric(Exception ex)</strong> handler at the bottom — it acts as a catch-all safety net, making sure that even <em>unexpected</em> errors (bugs, null pointer exceptions, database connectivity issues) never leak a raw stack trace to the client. This is especially important because internal error details (like database table names or file paths) can be a security risk if exposed publicly.</p><p>This is conceptually the same idea as an Express error-handling middleware (app.use((err, req, res, next) =&gt; {...})) — one centralized place that intercepts errors from anywhere in your app and formats the response consistently, instead of handling errors individually in every route.</p><h3>Transforming API Responses</h3><p>Beyond just handling errors consistently, many teams also standardize their <strong>successful</strong> responses into a consistent envelope, so every endpoint — regardless of what data it returns — follows the same shape. This makes life much easier for frontend developers consuming your API.</p><pre>public class ApiResponse&lt;T&gt; {<br>    private boolean success;<br>    private T data;<br>    private String message;<br><br>    public static &lt;T&gt; ApiResponse&lt;T&gt; success(T data) {<br>        ApiResponse&lt;T&gt; response = new ApiResponse&lt;&gt;();<br>        response.success = true;<br>        response.data = data;<br>        return response;<br>    }<br><br>    public static &lt;T&gt; ApiResponse&lt;T&gt; success(T data, String message) {<br>        ApiResponse&lt;T&gt; response = success(data);<br>        response.message = message;<br>        return response;<br>    }<br>    // getters<br>}</pre><pre>@PostMapping<br>public ResponseEntity&lt;ApiResponse&lt;UserResponseDTO&gt;&gt; createUser(@Valid @RequestBody UserRequestDTO request) {<br>    User user = userService.createUser(request.getName(), request.getEmail());<br>    ApiResponse&lt;UserResponseDTO&gt; response = ApiResponse.success(toResponseDTO(user), &quot;User created successfully&quot;);<br>    return ResponseEntity.status(HttpStatus.CREATED).body(response);<br>}</pre><p>This produces a response like:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;data&quot;: { &quot;id&quot;: 1, &quot;name&quot;: &quot;Rahul&quot;, &quot;email&quot;: &quot;rahul@example.com&quot; },<br>  &quot;message&quot;: &quot;User created successfully&quot;<br>}</pre><p>ApiResponse&lt;T&gt; here is a <strong>generic class</strong> — the &lt;T&gt; means it can wrap <em>any</em> type of data (a single user, a list of users, a page of results) while keeping the outer envelope identical every time. This pairs naturally with the mapping logic we wrote in Part 2 (toResponseDTO) — the DTO conversion controls <em>what</em> data looks like, and the response wrapper controls <em>how</em> it&#39;s packaged for the client.</p><p>Whether you use a wrapper like this or return raw DTOs directly (as we did in Part 2) is largely a team/API design decision — both are common in real-world Spring Boot codebases. What matters is being <strong>consistent</strong> across your entire API.</p><h3>Java 8 Lambda Expressions and the Stream API</h3><p>You’ve already seen a few examples of this (.stream().map(...).collect(...)) without a full explanation — let&#39;s fix that, because these two features appear in nearly every modern Spring Boot codebase.</p><h4>Lambda Expressions</h4><p>A <strong>lambda expression</strong> is a short, anonymous function — Java’s answer to JavaScript’s arrow functions.</p><pre>// Before Java 8: an anonymous inner class just to sort a list<br>Collections.sort(users, new Comparator&lt;User&gt;() {<br>    @Override<br>    public int compare(User a, User b) {<br>        return a.getName().compareTo(b.getName());<br>    }<br>});<br><br>// With a lambda expression:<br>Collections.sort(users, (a, b) -&gt; a.getName().compareTo(b.getName()));</pre><p>The (a, b) -&gt; a.getName().compareTo(b.getName()) part is the lambda — it says &quot;given two users a and b, return the result of comparing their names.&quot; It&#39;s the direct equivalent of JavaScript&#39;s users.sort((a, b) =&gt; a.name.localeCompare(b.name)).</p><p>A lambda can only be used where Java expects a <strong>functional interface</strong> — an interface with exactly one abstract method (like Comparator, which has one method: compare). Spring and Java&#39;s standard library are full of these: Runnable, Function&lt;T, R&gt;, Predicate&lt;T&gt;, Consumer&lt;T&gt;, and more.</p><h4>The Stream API</h4><p>A <strong>Stream</strong> lets you process collections (like List&lt;User&gt;) using a pipeline of operations — filter, transform, sort, collect — in a style very close to JavaScript&#39;s .filter(), .map(), and .reduce() chained together.</p><pre>List&lt;User&gt; users = userRepository.findAll();<br><br>// Get the names of all users whose email ends in &quot;@gmail.com&quot;, sorted alphabetically<br>List&lt;String&gt; gmailUserNames = users.stream()<br>        .filter(user -&gt; user.getEmail().endsWith(&quot;@gmail.com&quot;))<br>        .map(User::getName)<br>        .sorted()<br>        .collect(Collectors.toList());</pre><p>Breaking this down:</p><ul><li>.stream() — converts the List&lt;User&gt; into a Stream, so we can chain operations on it</li><li>.filter(user -&gt; ...) — keeps only users matching the condition (like JS&#39;s .filter())</li><li>.map(User::getName) — transforms each User into just their name (like JS&#39;s .map()). User::getName is a <strong>method reference</strong> — shorthand for the lambda user -&gt; user.getName()</li><li>.sorted() — sorts the results</li><li>.collect(Collectors.toList()) — converts the Stream back into a List (Streams are &quot;lazy&quot; and don&#39;t produce a real collection until you call a terminal operation like .collect())</li></ul><p>Other Stream operations worth knowing:</p><pre>// Count how many users match a condition<br>long count = users.stream().filter(u -&gt; u.getEmail().endsWith(&quot;@gmail.com&quot;)).count();<br><br>// Check if any/all users match a condition<br>boolean anyGmail = users.stream().anyMatch(u -&gt; u.getEmail().endsWith(&quot;@gmail.com&quot;));<br><br>// Find the first match<br>Optional&lt;User&gt; firstGmailUser = users.stream()<br>        .filter(u -&gt; u.getEmail().endsWith(&quot;@gmail.com&quot;))<br>        .findFirst();<br><br>// Group users by email domain<br>Map&lt;String, List&lt;User&gt;&gt; byDomain = users.stream()<br>        .collect(Collectors.groupingBy(u -&gt; u.getEmail().split(&quot;@&quot;)[1]));</pre><p>You’ll see this pattern constantly for one very practical reason: it lets you convert a List&lt;Entity&gt; into a List&lt;DTO&gt; in a single, readable line — exactly what we did back in Part 2&#39;s getAllUsers() endpoint:</p><pre>List&lt;UserResponseDTO&gt; users = userService.getAllUsers()<br>        .stream()<br>        .map(this::toResponseDTO)<br>        .toList();</pre><h3>Spring Web MVC — Wrapping Up</h3><p>Let’s consolidate everything from Parts 2 and 3 into one reference table of the core Spring Web MVC annotations you now know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*-glybP-opLukhhmz-bGGqQ.png" /></figure><p>At this point, you can build a fully functional, validated, well-structured REST API with clean error responses. That’s genuinely most of what a junior-to-mid backend role requires day to day for the “Web” side of things. What’s still missing is a deeper understanding of how data actually gets stored and retrieved — which is exactly what we tackle next.</p><h3>What We Covered</h3><ul><li><strong>PUT</strong> replaces a full resource; <strong>PATCH</strong> updates only the provided fields; <strong>DELETE</strong> removes it, typically returning 204 No Content.</li><li><strong>Bean Validation</strong> annotations (@NotBlank, @Email, @Size, etc.) combined with @Valid give you declarative input validation with almost no boilerplate.</li><li>You can build <strong>custom validation annotations</strong> backed by injectable Spring Beans, enabling checks like “this email must be unique” directly on your DTO.</li><li><strong>@RestControllerAdvice</strong> centralizes exception handling, ensuring your API never leaks raw stack traces and always returns a consistent error shape.</li><li>Wrapping successful responses in a generic <strong>ApiResponse&lt;T&gt;</strong> envelope gives your entire API a predictable, consistent shape.</li><li><strong>Lambda expressions</strong> are Java’s version of arrow functions; the <strong>Stream API</strong> lets you filter/map/collect collections in a style very close to JavaScript’s array methods — and it’s the standard way to convert Entities into DTOs across a list.</li></ul><p>In <strong>Part 4</strong>, we go deep into the persistence layer: installing MySQL, understanding Hibernate and JPA properly, writing dynamic query methods, sorting and pagination, projections, the entity lifecycle, and how to model real-world relationships (OneToOne, OneToMany, ManyToMany) — including performance pitfalls like the N+1 query problem.</p><p><em>This is Part 3 of a 6-part “Spring Boot for Full-Stack Developers” series. Catch up on Part 1 (Spring fundamentals) and Part 2 (building your first REST API) if you haven’t already.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce3ea01c72c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 2: Building Your First REST API (MVC, Tomcat…]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-2-building-your-first-rest-api-mvc-tomcat-d071ec25bf68?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/d071ec25bf68</guid>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 06:26:01 GMT</pubDate>
            <atom:updated>2026-08-19T06:26:01.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Full-Stack Developers — Part 2: Building Your First REST API (MVC, Tomcat, DispatcherServlet, and the Three-Layer Architecture)</h3><p><em>Part 2 of a 6-part series taking you from Java/Spring beginner to full-stack developer. If you haven’t read Part 1 (Spring fundamentals, Beans, Dependency Injection, Maven), start there first — everything here builds on it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBnkEnfe9GLheGIJvtszMg.png" /></figure><p>In Part 1, we covered <em>why</em> Spring exists and how it manages objects for you through Beans and Dependency Injection. Now it’s time to get practical: we’re going to build a real REST API, and along the way, understand exactly what happens between a client sending a request and your code responding with data.</p><p>By the end of this part, you’ll understand:</p><ul><li>What MVC architecture means in a Spring Boot context</li><li>What Tomcat and the DispatcherServlet actually do with every request</li><li>How to structure your code into three clean layers: <strong>Presentation</strong>, <strong>Service</strong>, and <strong>Persistence</strong></li><li>How to build a Controller, DTOs, an Entity, a Repository, and a Service — all working together</li></ul><p>We’ll build this around one running example throughout the series: a simple <strong>User Management API</strong>.</p><h3>Setting Up the Project</h3><p>The easiest way to start a Spring Boot project is <a href="https://start.spring.io/">Spring Initializr</a> — think of it like npm init combined with automatically installing a curated set of starter packages.</p><p>For this project, you’d select these dependencies:</p><ul><li><strong>Spring Web</strong> (spring-boot-starter-web) — gives you everything needed to build REST APIs, including the embedded Tomcat server</li><li><strong>Spring Data JPA</strong> (spring-boot-starter-data-jpa) — gives you the persistence layer tools we&#39;ll use later in this article</li><li><strong>MySQL Driver</strong> (or H2 for an in-memory database while learning)</li></ul><p>Once downloaded and unzipped, you’ll have a pom.xml (remember Maven from Part 1?) with those dependencies already listed, and a single class with a main() method annotated @SpringBootApplication — exactly what we saw in Part 1.</p><h3>What Does “MVC” Actually Mean Here?</h3><p>MVC stands for <strong>Model-View-Controller</strong>, a pattern for organizing code by separating three concerns:</p><ul><li><strong>Model</strong> — your data and business objects (in Spring, this maps to your Entities and DTOs)</li><li><strong>View</strong> — what gets shown to the user</li><li><strong>Controller</strong> — receives requests and decides what should happen</li></ul><p>If you’ve worked with a traditional server-rendered framework, “View” usually means an HTML template. But since we’re building a <strong>REST API</strong> (not a server-rendered website), there is no HTML view — our “View” is simply the <strong>JSON response</strong> that Spring automatically converts our Java objects into. This is the same shift you’d recognize from Express: an Express route handler that does res.json(data) isn&#39;t rendering a view either — it&#39;s just serializing data as a response, exactly like Spring does.</p><p>So in the REST-API version of MVC that we’ll use throughout this series:</p><ul><li><strong>Model</strong> = the data (Entities, DTOs)</li><li><strong>Controller</strong> = handles incoming HTTP requests and returns data</li><li><strong>“View”</strong> = JSON, automatically serialized by Spring — no template involved</li></ul><p>Spring’s implementation of this pattern is called <strong>Spring MVC</strong>, and it’s the module responsible for everything related to handling HTTP requests in a Spring Boot application.</p><h3>Tomcat — The Engine That Actually Talks HTTP</h3><p>Before your Java code ever runs, <em>something</em> has to open a network socket, listen on a port, understand raw HTTP requests, and pass them along. That’s <strong>Apache Tomcat</strong>’s job — it’s a <strong>Servlet Container</strong>, meaning it knows how to run Java web applications built using the Servlet API (Java’s low-level standard for handling HTTP requests, dating back to the late 1990s).</p><p>In older Java setups, you’d have to install Tomcat separately, package your app as a .war file, and manually deploy it onto that server. Spring Boot eliminates this entirely by embedding Tomcat <em>inside</em> your application — it&#39;s just another JAR dependency pulled in by spring-boot-starter-web. When you run your Spring Boot app, an embedded Tomcat instance starts up on port 8080 (by default) as part of the same process. There&#39;s nothing extra to install or configure.</p><p>This is roughly equivalent to how Node’s http.createServer() (which Express wraps) opens a port and listens for raw requests — Tomcat is doing the same fundamental job, just as a heavier, more feature-complete Java component with a long history in enterprise systems.</p><h3>The DispatcherServlet — Spring’s “Front Controller”</h3><p>Here’s where it gets interesting. Tomcat receives raw HTTP requests, but it doesn’t know anything about <em>your</em> Controllers, routes, or business logic. So Tomcat hands off every incoming request to a single, central component that Spring registers: the <strong>DispatcherServlet</strong>.</p><p>The DispatcherServlet implements something called the <strong>Front Controller pattern</strong> — instead of every URL path being handled by a separate, independent handler (which is common in very simple setups), <strong>all requests flow through one single entry point first</strong>, which then figures out where to send them.</p><p>Here’s the actual journey a request takes:</p><pre>1. Client sends: POST /api/users  { &quot;name&quot;: &quot;Rahul&quot;, &quot;email&quot;: &quot;rahul@example.com&quot; }<br>                        │<br>                        ▼<br>2. Tomcat receives the raw HTTP request on port 8080<br>                        │<br>                        ▼<br>3. Tomcat hands it to the DispatcherServlet (Spring&#39;s front controller)<br>                        │<br>                        ▼<br>4. DispatcherServlet asks the HandlerMapping: <br>   &quot;which Controller method handles POST /api/users?&quot;<br>                        │<br>                        ▼<br>5. HandlerMapping finds your @PostMapping(&quot;/api/users&quot;) method<br>                        │<br>                        ▼<br>6. DispatcherServlet converts the JSON body into a Java object (via Jackson)<br>   and calls your Controller method with it<br>                        │<br>                        ▼<br>7. Your Controller method runs (calls Service → Repository → Database)<br>                        │<br>                        ▼<br>8. Controller returns a Java object<br>                        │<br>                        ▼<br>9. DispatcherServlet converts that Java object BACK into JSON<br>                        │<br>                        ▼<br>10. Response sent back to the client</pre><p>If you’ve used Express, this concept isn’t foreign at all — Express’s router, under the hood, is also doing pattern matching to figure out which handler function should run for a given method + path combination. The DispatcherServlet is doing the same job, just with more moving parts (HandlerMapping, HandlerAdapter, ViewResolver, message converters) because Spring MVC was designed to support many different kinds of applications, not just JSON APIs.</p><p>The important takeaway: <strong>you never talk to Tomcat or the DispatcherServlet directly.</strong> You just write a Controller method and annotate it — Spring wires up all the routing machinery behind the scenes.</p><h3>Now Let’s Build It: The Three-Layer Architecture</h3><p>Real Spring Boot applications are almost always organized into three layers, each with one clear responsibility:</p><pre>Presentation Layer (Controller + DTO)<br>        │<br>        ▼<br>Service Layer (business logic)<br>        │<br>        ▼<br>Persistence Layer (Repository + Entity)<br>        │<br>        ▼<br>     Database</pre><p>Let’s build each one for our User Management API.</p><h4>1. The Persistence Layer — Entity and Repository</h4><p>The persistence layer is responsible for talking to the database. It has two parts: the <strong>Entity</strong> (a Java class that maps to a database table) and the <strong>Repository</strong> (an interface that gives you database operations without writing SQL).</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    @Column(unique = true)<br>    private String email;<br><br>    private LocalDateTime createdAt;<br><br>    // constructors, getters, and setters<br>}</pre><ul><li>@Entity tells Spring (specifically, Hibernate, which we&#39;ll cover fully in Part 4) that this class maps to a database table.</li><li>@Id marks the primary key field.</li><li>@GeneratedValue tells the database to auto-increment the ID for us.</li><li>@Column(unique = true) adds a database-level constraint.</li></ul><p>Now the Repository:</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    // that&#39;s it — no implementation needed<br>}</pre><p>This one line gives you save(), findById(), findAll(), deleteById(), and more — all implemented automatically by Spring Data JPA at runtime. We&#39;ll go much deeper into this (including writing your own custom queries) in Part 4, but for now, know that extending JpaRepository&lt;User, Long&gt; (where User is the entity and Long is the type of its ID) is enough to get full CRUD functionality with zero SQL written by you.</p><p>If you’re coming from Node.js, this is conceptually similar to what an ORM like Prisma or Sequelize gives you — except here, the Repository interface itself becomes a Spring Bean automatically, ready to be injected wherever it’s needed (remember DI from Part 1?).</p><h4>2. The Service Layer — Business Logic</h4><p>The Service layer sits between your Controller and your Repository. Its job is to hold <strong>business logic</strong> — validation rules, calculations, coordination between multiple repositories, anything that isn’t purely “talk to the database” or purely “handle an HTTP request.”</p><pre>@Service<br>public class UserService {<br><br>    private final UserRepository userRepository;<br><br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    public User createUser(String name, String email) {<br>        if (userRepository.findByEmail(email).isPresent()) {<br>            throw new IllegalStateException(&quot;Email already registered&quot;);<br>        }<br>        User user = new User();<br>        user.setName(name);<br>        user.setEmail(email);<br>        user.setCreatedAt(LocalDateTime.now());<br>        return userRepository.save(user);<br>    }<br><br>    public User getUserById(Long id) {<br>        return userRepository.findById(id)<br>                .orElseThrow(() -&gt; new NoSuchElementException(&quot;User not found&quot;));<br>    }<br><br>    public List&lt;User&gt; getAllUsers() {<br>        return userRepository.findAll();<br>    }<br>}</pre><p>Why not just put this logic directly inside the Controller? Two reasons:</p><ol><li><strong>Separation of concerns.</strong> The Controller’s job is to deal with HTTP — reading requests, returning responses, setting status codes. It shouldn’t also be responsible for deciding <em>what counts as a duplicate email</em> or <em>how a user gets created</em>. Mixing these makes your code harder to read and harder to change.</li><li><strong>Reusability and testability.</strong> If your business logic lives in the Service layer, you can call it from multiple places (a REST Controller, a scheduled batch job, a message queue listener) without duplicating logic. And exactly like we discussed in Part 1’s “hard to test” problem, a UserService that depends on UserRepository through its constructor can be tested in isolation, with a fake repository, with zero web server involved.</li></ol><h4>3. The Presentation Layer — Controller and DTOs</h4><p>This is the layer that actually talks to the outside world.</p><p><strong>First, a critical question: why not just accept and return the </strong><strong>User entity directly in your API?</strong></p><p>You <em>could</em>, but it’s considered bad practice, for a few solid reasons:</p><ul><li><strong>You’d leak internal database structure to clients.</strong> If you add an internal-only field to your User entity (like a passwordHash or an internal version column used for auditing), it would automatically appear in your API responses unless you&#39;re careful.</li><li><strong>You lose control over what a client is allowed to send.</strong> If clients can POST a raw User object, what stops them from setting their own id or createdAt fields?</li><li><strong>Entities are often tied to database-specific behavior</strong> (like lazy-loaded relationships), which can cause confusing bugs or errors when Spring tries to convert them directly into JSON.</li></ul><p>The solution is a <strong>DTO — Data Transfer Object</strong>. A DTO is just a plain class that defines exactly what shape of data goes <em>in</em> to your API and what shape goes <em>out</em> — completely separate from your database structure.</p><pre>// What the client sends when creating a user<br>public class UserRequestDTO {<br>    private String name;<br>    private String email;<br>    // getters and setters<br>}<br><br>// What we send back to the client<br>public class UserResponseDTO {<br>    private Long id;<br>    private String name;<br>    private String email;<br>    private LocalDateTime createdAt;<br>    // getters and setters, constructor<br>}</pre><p>Now the Controller:</p><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br><br>    private final UserService userService;<br><br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;UserResponseDTO&gt; createUser(@RequestBody UserRequestDTO request) {<br>        User user = userService.createUser(request.getName(), request.getEmail());<br>        UserResponseDTO response = toResponseDTO(user);<br>        return ResponseEntity.status(HttpStatus.CREATED).body(response);<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;UserResponseDTO&gt; getUser(@PathVariable Long id) {<br>        User user = userService.getUserById(id);<br>        return ResponseEntity.ok(toResponseDTO(user));<br>    }<br><br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;UserResponseDTO&gt;&gt; getAllUsers() {<br>        List&lt;UserResponseDTO&gt; users = userService.getAllUsers()<br>                .stream()<br>                .map(this::toResponseDTO)<br>                .toList();<br>        return ResponseEntity.ok(users);<br>    }<br><br>    private UserResponseDTO toResponseDTO(User user) {<br>        return new UserResponseDTO(user.getId(), user.getName(), user.getEmail(), user.getCreatedAt());<br>    }<br>}</pre><p>Let’s break down the annotations, since these are the ones you’ll use constantly:</p><ul><li>@RestController — a combination of @Controller (marks it as a Bean handling web requests) and @ResponseBody (tells Spring to serialize return values directly into the HTTP response body as JSON, instead of trying to resolve a view template). This is <em>the</em> annotation for REST APIs.</li><li>@RequestMapping(&quot;/api/users&quot;) — sets a base path for every endpoint in this Controller (similar to router.use(&#39;/api/users&#39;, usersRouter) in Express).</li><li>@PostMapping, @GetMapping — map HTTP methods to specific Java methods, equivalent to Express&#39;s router.post(...) and router.get(...).</li><li>@RequestBody — tells Spring &quot;parse the incoming JSON body into this object&quot; (Jackson, Spring&#39;s default JSON library, handles the actual conversion).</li><li>@PathVariable — extracts a value from the URL path, like :id in an Express route (/users/:id).</li><li>ResponseEntity&lt;T&gt; — lets you control the full HTTP response: status code, headers, and body, rather than just returning raw data and letting Spring guess the status code.</li></ul><p>Notice the .stream().map(...).toList() call in getAllUsers() — that&#39;s Java 8&#39;s Stream API, transforming a List&lt;User&gt; into a List&lt;UserResponseDTO&gt; in a single readable line, similar to JavaScript&#39;s .map() on arrays. We&#39;ll dedicate a full section to Streams and Lambdas in Part 3, since they show up constantly in real Spring codebases.</p><h3>Tracing a Full Request, End to End</h3><p>Let’s connect everything by tracing what happens when a client sends:</p><pre>POST /api/users<br>{ &quot;name&quot;: &quot;Rahul&quot;, &quot;email&quot;: &quot;rahul@example.com&quot; }</pre><ol><li><strong>Tomcat</strong> receives the raw HTTP request on port 8080.</li><li><strong>DispatcherServlet</strong> receives it from Tomcat and asks HandlerMapping which Controller method matches POST /api/users.</li><li>It finds UserController.createUser(), converts the JSON body into a UserRequestDTO object (via Jackson), and calls the method.</li><li><strong>UserController</strong> calls userService.createUser(name, email).</li><li><strong>UserService</strong> checks for a duplicate email, builds a User entity, and calls userRepository.save(user).</li><li><strong>UserRepository</strong> (backed by Spring Data JPA and Hibernate) generates and runs the actual SQL INSERT statement against the database.</li><li>The saved User object (now with a generated id) flows back up: Repository → Service → Controller.</li><li><strong>UserController</strong> converts the User entity into a UserResponseDTO.</li><li><strong>DispatcherServlet</strong> serializes that DTO into JSON.</li><li><strong>Tomcat</strong> sends the JSON response back to the client, with status 201 Created.</li></ol><p>Every one of the objects involved here — UserController, UserService, UserRepository — is a <strong>Bean</strong>, created and wired together by Spring&#39;s IoC container exactly as we covered in Part 1. That&#39;s the payoff of understanding DI early: once you see it, this entire flow stops looking like magic annotations and starts looking like a clear, traceable chain of objects calling each other.</p><h3>What We Covered</h3><ul><li><strong>MVC</strong> in a REST API context means Controller (handles requests) + Model (Entities/DTOs) + JSON as the “View.”</li><li><strong>Tomcat</strong> is the embedded server that actually receives raw HTTP requests.</li><li>The <strong>DispatcherServlet</strong> is Spring’s front controller — every request passes through it first, and it routes the request to the correct Controller method.</li><li>Well-structured Spring Boot apps are split into three layers:</li><li><strong>Persistence</strong> (Entity + Repository) — talks to the database</li><li><strong>Service</strong> (business logic) — coordinates and validates</li><li><strong>Presentation</strong> (Controller + DTO) — handles HTTP in and out</li><li><strong>DTOs</strong> exist to keep your API contract separate from your database structure — never expose Entities directly.</li></ul><p>In <strong>Part 3</strong>, we’ll extend this Controller with PUT, PATCH, and DELETE endpoints, add proper input validation (including writing your own custom validation annotations), build centralized exception handling so your API returns clean error responses instead of stack traces, and take a closer look at Java 8&#39;s Lambda expressions and Stream API.</p><p><em>This is Part 2 of a 6-part “Spring Boot for Full-Stack Developers” series. Part 1 covered Spring fundamentals, Beans, and Dependency Injection — read that first if you haven’t already.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d071ec25bf68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Full-Stack Developers — Part 1: Why Spring Exists (It’s Not Just “Java’s Express.js”]]></title>
            <link>https://medium.com/@rahul281191/spring-boot-for-full-stack-developers-part-1-why-spring-exists-its-not-just-java-s-express-js-b47c354606eb?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47c354606eb</guid>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 04:51:53 GMT</pubDate>
            <atom:updated>2026-08-18T04:51:53.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Full-Stack Developers — Part 1: Why Spring Exists (It’s Not Just “Java’s Express.js”)</h3><p><em>Part 1 of a 6-part series that takes you from “I’ve never touched Java” to building production-ready, secure, full-stack applications with Spring Boot.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qABcUCPYnZG6XGETCxaz4g.png" /></figure><p>If you’ve built backends in Node.js and are now looking at a Spring Boot codebase for the first time, you’ve probably felt one of two things: either “this looks like way too much boilerplate for a simple API,” or “why does this framework need so many annotations to do what I do in five lines of Express code?”</p><p>Both reactions are fair. But they usually come from evaluating Spring using Node.js’s rulebook. Spring wasn’t built to be “Express for Java.” It was built to solve a completely different set of problems that Java developers were facing in the early 2000s — problems that Node.js, by virtue of being younger and simpler, mostly sidestepped.</p><p>This part lays the foundation. Once you understand <em>why</em> Spring exists, everything else in this series — Beans, Dependency Injection, Auto-Configuration — stops feeling like magic and starts feeling like common sense.</p><h3>What is the Spring Framework?</h3><p>Spring is a framework for building Java applications — most commonly backend/server-side applications — that takes care of <strong>object creation, object wiring, and application infrastructure</strong>, so you can focus on writing business logic instead of plumbing code.</p><p>It was created in 2003 by Rod Johnson, largely as a reaction against <strong>Java EE (Enterprise Edition)</strong>, which at the time was the “official” way to build enterprise Java applications. Java EE was powerful but painfully heavy — you needed an application server, tons of XML configuration, and verbose interfaces just to do basic things. Spring offered a lighter, simpler, more flexible alternative, and it eventually became the dominant way to build Java backend applications.</p><p>Think of Spring as a very large toolbox. It gives you:</p><ul><li>A way to create and manage objects for you (<strong>IoC Container</strong>)</li><li>A way to build web applications (<strong>Spring MVC</strong>)</li><li>A way to talk to databases (<strong>Spring Data</strong>)</li><li>A way to secure your application (<strong>Spring Security</strong>)</li><li>And dozens of other modules for messaging, batch processing, testing, etc.</li></ul><p><strong>Spring Boot</strong>, which we’ll compare properly later in this article, is built <em>on top of</em> Spring Framework to make all of this dramatically easier to set up.</p><h3>How Is This Different From Node.js?</h3><p>This is the mental model shift that matters most, so let’s be explicit about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ziy9NF0TdOiVCjdqFdxP-A.png" /></figure><p>The single biggest difference isn’t syntax — it’s <strong>who is in control of creating objects</strong>.</p><p>In Node/Express, <em>you</em> are always in control:</p><pre>// userService.js<br>const UserRepository = require(&#39;./userRepository&#39;);<br><br>class UserService {<br>  constructor() {<br>    this.userRepository = new UserRepository(); // you create it yourself<br>  }<br><br>  getUser(id) {<br>    return this.userRepository.findById(id);<br>  }<br>}<br><br>module.exports = UserService;</pre><p>In Spring, you <em>describe</em> what you need, and the framework hands it to you:</p><pre>@Service<br>public class UserService {<br><br>    private final UserRepository userRepository;<br><br>    // Spring creates a UserRepository object and &quot;injects&quot; it here automatically<br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    public User getUser(Long id) {<br>        return userRepository.findById(id).orElseThrow();<br>    }<br>}</pre><p>That one shift — from “I create what I need” to “I declare what I need, and something else provides it” — is called <strong>Inversion of Control (IoC)</strong>, and it’s the entire reason Spring exists. Let’s understand exactly what problems it solves.</p><h3>The 3 Major Problems Spring Solves</h3><p>Imagine a mid-sized Java application <em>without</em> Spring. No framework, just plain Java classes calling new on each other. Three problems show up almost immediately as the app grows.</p><h4>Problem 1: Tight Coupling</h4><p>“Tight coupling” means one class is hard-wired to a specific implementation of another class, instead of depending on an abstraction.</p><pre>public class OrderService {<br>    private EmailNotifier notifier = new EmailNotifier(); // hard-coded dependency<br><br>    public void placeOrder(Order order) {<br>        // ... business logic<br>        notifier.send(&quot;Order placed!&quot;);<br>    }<br>}</pre><p>Here, OrderService is glued to EmailNotifier. What happens when your product team says &quot;we also need to send SMS notifications&quot; or &quot;let&#39;s switch to push notifications&quot;? You have to go back into OrderService and change its internals — even though placing an order and sending a notification are two completely different concerns.</p><p>The fix is to depend on an <strong>interface</strong>, not a concrete class:</p><pre>public interface Notifier {<br>    void send(String message);<br>}<br><br>public class EmailNotifier implements Notifier {<br>    public void send(String message) { /* send email */ }<br>}<br><br>public class SmsNotifier implements Notifier {<br>    public void send(String message) { /* send SMS */ }<br>}<br><br>public class OrderService {<br>    private Notifier notifier; // depends on the abstraction, not a specific class<br><br>    public OrderService(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br>    // ...<br>}</pre><p>Now OrderService doesn&#39;t care <em>which</em> notifier it gets — email, SMS, or a mock one for testing. But someone still has to decide, at some point, &quot;give OrderService an EmailNotifier.&quot; Without a framework, that decision-making code (called &quot;wiring&quot;) has to live somewhere, and as your app grows to hundreds of classes, that wiring becomes a nightmare to manage by hand. This is exactly what Spring&#39;s container does for you — more on that in the Beans and DI sections below.</p><h4>Problem 2: Hard to Test</h4><p>Tight coupling directly causes this second problem. If OrderService creates its own EmailNotifier with new EmailNotifier(), how do you write a unit test for OrderService without actually sending a real email every time you run your tests?</p><p>You can’t — not easily. You’d need to either let the real email get sent (slow, unreliable, and you don’t want emails going out during test runs) or restructure your code just to make it testable.</p><p>Once you depend on an interface (as shown above), testing becomes trivial — you can pass in a <strong>fake/mock</strong> Notifier that does nothing but record what was called:</p><pre>public class FakeNotifier implements Notifier {<br>    public String lastMessage;<br>    public void send(String message) {<br>        this.lastMessage = message; // just record it, don&#39;t actually send anything<br>    }<br>}<br><br>// In your test:<br>FakeNotifier fakeNotifier = new FakeNotifier();<br>OrderService orderService = new OrderService(fakeNotifier);<br>orderService.placeOrder(someOrder);<br>assert fakeNotifier.lastMessage.equals(&quot;Order placed!&quot;);</pre><p>This pattern — designing your code so dependencies can be swapped for test doubles — is one of the core reasons Java applications are built around interfaces and dependency injection, and Spring makes this pattern the <em>default</em> way of working rather than something you have to fight for.</p><h4>Problem 3: Scattered Object Creation</h4><p>In a real application, dozens of classes depend on each other. OrderService needs a Notifier and a PaymentGateway. PaymentGateway needs an HttpClient and some ApiConfig. UserController needs a UserService, which needs a UserRepository, which needs a DataSource.</p><p>Without a framework, <em>somewhere</em> — usually in a giant main() method or a tangle of factory classes — you end up manually writing:</p><pre>DataSource dataSource = new DataSource(dbUrl, dbUser, dbPassword);<br>UserRepository userRepository = new UserRepository(dataSource);<br>UserService userService = new UserService(userRepository);<br>Notifier notifier = new EmailNotifier();<br>PaymentGateway paymentGateway = new PaymentGateway(new HttpClient(), new ApiConfig());<br>OrderService orderService = new OrderService(notifier, paymentGateway);<br>UserController userController = new UserController(userService);<br>OrderController orderController = new OrderController(orderService);<br>// ...and this list keeps growing for every class in your app</pre><p>This is called “scattered object creation” — the logic for <em>how to build</em> your objects is smeared across your codebase, duplicated, and painful to change. Change one constructor signature, and you might have to update object-creation code in five different places.</p><p><strong>Spring’s answer to all three problems is the same: let a central container own the responsibility of creating objects and wiring their dependencies together.</strong> That container is what we look at next.</p><h3>Beans in Spring Framework — What and Why?</h3><p>A <strong>Bean</strong> is simply a Java object that is created, configured, and managed by the Spring container instead of by your own code with new.</p><p>That’s it. There’s no special syntax a class needs to “become” a Bean — any regular Java object can be one. What makes it a Bean is that <strong>Spring is the one responsible for creating it, and Spring keeps a reference to it so it can hand it out wherever it’s needed.</strong></p><p>You tell Spring “this class should be a Bean” using annotations like @Component, @Service, @Repository, or @Controller (these are all specialized versions of @Component — Spring treats them almost identically, but the different names help communicate what each class does):</p><pre>@Service // Tells Spring: &quot;create and manage one instance of this class&quot;<br>public class UserService {<br>    // ...<br>}</pre><p>When your application starts, Spring scans your codebase, finds all classes marked this way, creates an instance of each one, and stores them in a container called the <strong>ApplicationContext</strong> (we’ll cover this fully later in this article).</p><h4>Why does this matter?</h4><p>Because it solves Problem 3 directly. Instead of you manually writing new UserService(new UserRepository(new DataSource(...))), you just tell Spring &quot;here&#39;s a class, manage it,&quot; and Spring figures out how to build it — including all of <em>its</em> dependencies, recursively.</p><p>By default, a Bean in Spring is a <strong>singleton</strong> — meaning Spring creates exactly <em>one</em> instance of it and reuses that same instance every time it’s needed anywhere in your app. This is different from Node.js, where if you require() the same module in two files, you get the same cached module object too (Node&#39;s module caching does something conceptually similar) — but in Spring, this singleton behavior is an explicit, configurable feature of how Beans work, and you can change it (e.g., to create a new instance per request) when needed.</p><h3>Dependency Injection in Spring Framework</h3><p>If Beans are the <em>objects</em> Spring manages, <strong>Dependency Injection (DI)</strong> is the <em>mechanism</em> Spring uses to give those objects to the classes that need them.</p><p>Remember Problem 1 (tight coupling)? We fixed it by making OrderService depend on the Notifier interface instead of creating EmailNotifier itself. But something still needs to hand OrderService an actual EmailNotifier object at runtime. In plain Java, that&#39;s you, manually, in a constructor call. In Spring, that&#39;s the <strong>DI mechanism</strong>, automatically.</p><p>There are three common ways to do this in Spring:</p><ol><li><strong>Constructor Injection (recommended, and what you’ll see most in modern Spring code):</strong></li></ol><pre>@Service<br>public class OrderService {<br><br>    private final Notifier notifier;<br>    private final PaymentGateway paymentGateway;<br><br>    // Spring sees this constructor and automatically supplies<br>    // a Notifier Bean and a PaymentGateway Bean when creating OrderService<br>    public OrderService(Notifier notifier, PaymentGateway paymentGateway) {<br>        this.notifier = notifier;<br>        this.paymentGateway = paymentGateway;<br>    }<br>}</pre><p>2. Field Injection (common in tutorials, but generally discouraged in real projects):</p><pre>@Service<br>public class OrderService {<br><br>    @Autowired<br>    private Notifier notifier; // Spring injects this directly into the field<br>}</pre><p>3. Setter Injection (less common, used for optional dependencies):</p><pre>@Service<br>public class OrderService {<br>    private Notifier notifier;<br><br>    @Autowired<br>    public void setNotifier(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br>}</pre><p>Constructor injection is preferred because it makes dependencies explicit and mandatory (you literally cannot create an OrderService without providing a Notifier), and it makes the class much easier to unit test — you just call the constructor directly with fake objects, without needing Spring running at all.</p><h3>A Node.js parallel worth knowing</h3><p>If you’ve heard of <strong>NestJS</strong>, this will click instantly — NestJS was explicitly inspired by Spring’s architecture, and it brought Dependency Injection, decorators (similar to annotations), and a Module/Provider system to the Node.js world for exactly the same reasons described above. If you’ve used @Injectable() in NestJS, you&#39;ve already used DI — Spring just does the same thing, but it&#39;s the <em>original</em> framework that popularized this pattern for backend web apps, over a decade earlier.</p><h3>Spring Boot vs Spring Framework — A Comparison</h3><p>Now that you understand <em>why</em> Spring exists (IoC, Beans, DI), let’s clear up a common confusion: <strong>Spring Framework</strong> and <strong>Spring Boot</strong> are not competitors — Spring Boot is built <em>on top of</em> Spring Framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9zRChN4cp8iwJ0SxJGyXA.png" /></figure><p>Analogy for a Node.js developer: think of Spring Framework as the raw building blocks (similar to how Express gives you routing/middleware, but you assemble everything else yourself), and Spring Boot as something closer to a fully-configured starter template — auto-configured, with sensible defaults, similar in <em>spirit</em> to how a tool like create-react-app or Nest CLI sets up a working project structure for you instantly, except Spring Boot&#39;s auto-configuration goes much deeper — it&#39;s actively inspecting your dependencies at startup and configuring your entire application accordingly.</p><p>In modern Java development, you almost always use Spring Boot rather than raw Spring Framework — which is exactly what the rest of this series will focus on.</p><h3>Auto-Configuration, ApplicationContext, and the Internal Working of a Spring Boot App</h3><p>Let’s demystify what actually happens when you run a Spring Boot application. Every Spring Boot app starts with a class like this:</p><pre>@SpringBootApplication<br>public class MyApp {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApp.class, args);<br>    }<br>}</pre><p>Here’s what happens, step by step, when you run this main() method:</p><p><strong>1. </strong><strong>@SpringBootApplication kicks things off.</strong> This one annotation is actually a combination of three:</p><ul><li>@Configuration — marks this class as a source of Bean definitions</li><li>@EnableAutoConfiguration — tells Spring Boot to auto-configure things based on what&#39;s on your classpath (explained below)</li><li>@ComponentScan — tells Spring to scan this package (and sub-packages) for classes annotated with @Component, @Service, @Repository, @Controller, etc.</li></ul><p><strong>2. Component scanning happens.</strong> Spring walks through your codebase, finds every class marked as a Bean candidate, and notes them down — but doesn’t create them yet, just registers their “blueprints.”</p><p><strong>3. The ApplicationContext is created.</strong> This is the heart of Spring — think of it as a big container/registry that will hold every Bean in your application, along with the metadata needed to create and connect them. It’s sometimes called the “IoC Container.”</p><p><strong>4. Beans are instantiated and wired.</strong> The ApplicationContext goes through all the registered Bean blueprints and creates actual Java objects from them — resolving each one’s dependencies (via DI, as shown earlier) in the correct order. If OrderService needs a Notifier, Spring makes sure Notifier (or its implementation) is created first, then hands it to OrderService&#39;s constructor.</p><p><strong>5. Auto-Configuration kicks in.</strong> This is Spring Boot’s signature feature. Based on what dependencies (JAR files) it finds on your classpath, Spring Boot automatically configures relevant Beans for you. For example:</p><ul><li>If it sees spring-boot-starter-web on your classpath, it auto-configures an embedded Tomcat server and sets up Spring MVC.</li><li>If it sees a database driver like postgresql plus spring-boot-starter-data-jpa, it auto-configures a DataSource and JPA/Hibernate setup.</li><li>If it sees spring-boot-starter-security, it auto-configures a default security setup (which is why a fresh Spring Boot app with this dependency will unexpectedly ask you for a login password!).</li></ul><p>All of this is done through classes marked @ConditionalOnClass, @ConditionalOnMissingBean, etc. — meaning &quot;only configure this Bean IF a certain class exists on the classpath AND the developer hasn&#39;t already defined their own version of this Bean.&quot; This is what gives you sensible defaults <em>without</em> locking you out of overriding them.</p><p><strong>6. The embedded server starts</strong>, and your application begins listening for HTTP requests — with zero external server setup required.</p><p><strong>In short:</strong> Spring Boot inspects what you’ve included as dependencies, decides what infrastructure you probably need, and configures it automatically — while still letting you override any of it manually if you disagree with its defaults.</p><h3>Maven — The Build Tool Powering All of This</h3><p>If you’re coming from Node.js, <strong>Maven</strong> is Java’s equivalent of npm/yarn — but it does more than just manage dependencies. It also compiles your code, runs your tests, packages your app, and defines your project&#39;s structure, all through a single file: pom.xml (Project Object Model).</p><p>Here’s a minimal comparison:</p><p><strong>package.json (Node.js):</strong></p><pre>{<br>  &quot;name&quot;: &quot;my-app&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.18.2&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  }<br>}</pre><p>pom.xml (Maven):</p><pre>&lt;project&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-app&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br><br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/project&gt;</pre><p>Key things to know about Maven:</p><ul><li><strong>Dependencies come from a central repository</strong> called Maven Central (similar to the npm registry), and Maven downloads them automatically the first time you build your project.</li><li><strong>Spring Boot “Starters”</strong> are a huge convenience Maven dependencies give you — instead of manually picking 10 different compatible libraries for building a web app, you add ONE dependency: spring-boot-starter-web, and it pulls in everything needed (embedded Tomcat, Spring MVC, Jackson for JSON, etc.) at compatible versions.</li><li><strong>Maven has a build lifecycle</strong> — a sequence of phases that run in order: validate → compile → test → package → install → deploy. Running mvn package, for example, automatically runs validate, compile, and test first, then packages your app into a runnable .jar file.</li><li><strong>Common commands you’ll actually use:</strong></li><li>mvn clean install — deletes old build files, compiles, runs tests, and installs the package</li><li>mvn spring-boot:run — runs your Spring Boot app directly, similar to npm start</li><li>mvn test — runs your test suite, similar to npm test</li></ul><p>There’s also <strong>Gradle</strong>, a newer, more flexible build tool that many projects use instead of Maven (it uses a build.gradle file with a more programmatic syntax). Both do fundamentally the same job — for this series, we&#39;ll stick with Maven since it&#39;s the more common starting point for beginners.</p><h3>What We Covered</h3><ul><li>Spring exists to solve three concrete problems: <strong>tight coupling</strong>, <strong>hard-to-test code</strong>, and <strong>scattered object creation</strong>.</li><li><strong>Beans</strong> are just regular Java objects that Spring creates and manages for you, instead of you calling new yourself.</li><li><strong>Dependency Injection</strong> is how Spring hands those Beans to the classes that need them — usually through constructor parameters.</li><li><strong>Spring Boot</strong> sits on top of <strong>Spring Framework</strong>, adding auto-configuration, an embedded server, and starter dependencies to eliminate hours of manual setup.</li><li>When a Spring Boot app starts, it scans for Beans, builds an <strong>ApplicationContext</strong>, wires everything together via DI, and auto-configures infrastructure based on what’s on your classpath.</li><li><strong>Maven</strong> manages your dependencies and build process, similar to npm — but with a defined lifecycle and a central repository of pre-built libraries.</li></ul><p>In <strong>Part 2</strong>, we’ll move from theory to practice: setting up your first real Spring Boot project, understanding MVC architecture, how Tomcat and the DispatcherServlet actually route a request through your app, and building your first Controller, DTO, and Service layer.</p><p><em>This is Part 1 of a 6-part “Spring Boot for Full-Stack Developers” series. Follow along for Part 2, where we start writing our first REST API.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47c354606eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: From Zero to Google — Part 3]]></title>
            <link>https://medium.com/@rahul281191/system-design-from-zero-to-google-part-3-2ec57fac32ac?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec57fac32ac</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 04:53:59 GMT</pubDate>
            <atom:updated>2026-08-06T04:53:59.016Z</atom:updated>
            <content:encoded><![CDATA[<h4>Large-Scale Systems, Distributed Concepts &amp; Interview Mastery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KN0QxPIFZ8Ythc8qT9ryTA.png" /></figure><p><em>This is the final part. We design systems at Google-scale, cover the distributed systems concepts that separate good candidates from great ones, and end with a complete interview strategy you can use on any question you’ve never seen before.</em></p><h4>What You Know After Parts 1 and 2</h4><p>By now you understand:</p><ul><li>Core infrastructure: DNS, CDN, Load Balancer, Cache, Replication</li><li>Data trade-offs: SQL vs NoSQL, CAP Theorem, Sharding strategies</li><li>Real systems: Rate Limiter, TinyURL, Instagram, Twitter, WhatsApp</li><li>Patterns: Fan-out on write vs read, WebSockets, Message queues, Microservices</li></ul><p>Part 3 covers the advanced concepts that separate senior candidates from everyone else. These are the topics where interviewers at Google and Meta expect precise reasoning, not just “we use Kafka.”</p><h3>Design 7: YouTube — Video at Global Scale</h3><p><em>Difficulty: Hard — asked at Google, Netflix, Meta, TikTok</em></p><h4>Why YouTube is architecturally unique</h4><p>Most systems deal with small data (text, numbers). YouTube deals with video files that are gigabytes each. The engineering challenges are different:</p><ol><li><strong>Upload:</strong> A 1GB video file cannot be uploaded in one HTTP request</li><li><strong>Processing:</strong> Raw video must be transcoded to multiple resolutions (360p, 720p, 1080p, 4K)</li><li><strong>Storage:</strong> YouTube stores 500 hours of video per minute. Storage cost is enormous.</li><li><strong>Streaming:</strong> Video must be delivered smoothly across terrible mobile connections</li></ol><h4>Requirements</h4><p><strong>Functional:</strong></p><ul><li>Users upload videos</li><li>Videos are available within minutes in multiple resolutions</li><li>Users stream videos smoothly</li><li>Users can search for videos</li><li>Recommendations (basic)</li></ul><p><strong>Non-functional (YouTube scale):</strong></p><ul><li>500 hours of video uploaded per minute</li><li>1 billion hours watched per day</li><li>99.9% availability for watch (less strict for upload)</li><li>Video start time &lt; 2 seconds even on slow connections</li><li>Support 2G to 8K connections (adaptive streaming)</li></ul><h4>Capacity Estimate</h4><pre>Uploads:<br>  500 hours/minute × 1GB/minute of raw video = 500GB/minute<br>  500GB/minute × 60 × 24 = 720TB/day of raw video<br>  After compression and multiple resolutions = ~300TB/day stored<br><br>Watches:<br>  1 billion hours/day = 41 million hours/hour = ~700,000 concurrent viewers<br>  At 5Mbps average bitrate = 3.5 Tbps of bandwidth needed<br>  This is why YouTube needs a CDN — no origin can serve 3.5Tbps</pre><h4>Video Upload — Chunked Upload</h4><p>You cannot upload a 1GB file as a single HTTP request. What if the connection drops at 990MB? You lose everything.</p><p><strong>Chunked Upload (resumable upload protocol):</strong></p><pre>Client splits video into 5MB chunks.<br><br>Upload chunk 1 (5MB) → Server: &quot;Received chunk 1, hash: abc123&quot;<br>Upload chunk 2 (5MB) → Server: &quot;Received chunk 2, hash: def456&quot;<br>...<br>[Connection drops!]<br>...<br>Client reconnects: &quot;I was uploading video V123, what chunks did you get?&quot;<br>Server: &quot;I have chunks 1-47&quot;<br>Client: &quot;Resuming from chunk 48...&quot;<br>Upload chunk 48 → Server → ...<br>Upload last chunk → Server: &quot;Upload complete. Processing...&quot;<br><br>This is exactly what YouTube, Google Drive, and S3 multipart upload use.</pre><h4>Video Processing Pipeline — The Hardest Part</h4><p>Raw video uploaded by user → Must become streamable video in multiple resolutions.</p><p>This is CPU-intensive work that cannot happen in the request-response cycle. It uses an asynchronous pipeline:</p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                   Video Processing Pipeline                       │<br>│                                                                   │<br>│  Raw Video                                                        │<br>│  Uploaded ──► Object Store (raw) ──► Kafka &quot;video.uploaded&quot;      │<br>│                                              │                    │<br>│                                       ┌──────▼───────┐           │<br>│                                       │  Processing  │           │<br>│                                       │  Orchestrator│           │<br>│                                       └──────┬───────┘           │<br>│                              ┌───────────────┼───────────────┐   │<br>│                              │               │               │   │<br>│                        ┌─────▼─────┐  ┌─────▼─────┐  ┌─────▼──┐│<br>│                        │ Transcoder │  │ Transcoder│  │Extract ││<br>│                        │ 360p      │  │ 1080p     │  │Thumbnail││<br>│                        └─────┬─────┘  └─────┬─────┘  └─────┬──┘│<br>│                              │               │               │   │<br>│                              └───────────────┴───────────────┘   │<br>│                                              │                    │<br>│                                       ┌──────▼───────┐           │<br>│                                       │  CDN Origin  │           │<br>│                                       │  (Object     │           │<br>│                                       │   Store)     │           │<br>│                                       └──────────────┘           │<br>└─────────────────────────────────────────────────────────────────┘</pre><p><strong>Why multiple transcoders in parallel?</strong></p><p>A 1-hour video at 4K takes ~30 minutes to transcode to 1080p if done sequentially. But if you split the video into 1-minute segments and transcode each segment in parallel on 30 machines, the whole video is transcoded in ~1 minute.</p><p>This is the same MapReduce principle — split the work, process in parallel, reassemble.</p><h4>Adaptive Bitrate Streaming (ABR) — How Smooth Streaming Works</h4><p>Why does YouTube not just send you the 1080p version and let it buffer?</p><p>Because your network speed fluctuates. You might have 100Mbps at home and 2Mbps on the train. ABR solves this:</p><pre>Video is broken into 10-second segments.<br>Each segment is available in multiple resolutions:<br>  segment_1_360p.mp4  (0.5MB)<br>  segment_1_720p.mp4  (2MB)<br>  segment_1_1080p.mp4 (5MB)<br>  segment_1_4k.mp4    (20MB)<br><br>A manifest file (HLS or DASH format) tells your player what&#39;s available.<br><br>Your player monitors download speed:<br>  Fast connection → Request 1080p segments<br>  Speed drops → Automatically switch to 720p segments<br>  Speed drops more → Switch to 360p (never buffers, but blurry)<br>  Speed recovers → Switch back up to 1080p<br><br>This is why YouTube shows &quot;360p&quot; in the corner sometimes —<br>your player chose it because it was the best option for your connection.<br><br>The player has a buffer: it downloads 30 seconds ahead.<br>Even if connection briefly drops, playback continues from buffer.</pre><h4>CDN Strategy — Serving 3.5 Tbps</h4><p>No origin server can serve YouTube’s traffic. The CDN does most of the work.</p><pre>Video storage tiers:<br><br>HOT content (recently uploaded, trending):<br>  Cached at hundreds of CDN edge locations worldwide.<br>  User watches → Served from nearest CDN edge.<br>  Latency: &lt; 10ms. Cost: higher per GB stored.<br><br>WARM content (moderately popular):<br>  Cached at regional CDN hubs (fewer locations).<br>  User watches → Served from regional hub.<br>  Latency: 20-50ms.<br><br>COLD content (old, rarely watched):<br>  Stored only in Google&#39;s origin object store.<br>  User watches → CDN fetches from origin, caches it for next viewer.<br>  Latency: 100-200ms for first viewer. Subsequent viewers get CDN.<br><br>98% of views are served by CDN.<br>Only 2% hit the origin (first view of cold content).</pre><h4>Why this matters for your interview</h4><p>When designing any video/media system, the three questions to always answer are:</p><ol><li>How is content uploaded? (chunked upload, what storage?)</li><li>How is it processed? (synchronous vs async pipeline, why async?)</li><li>How is it delivered? (CDN strategy, what about very popular vs unpopular content?)</li></ol><h3>Design 8: Google Search (Web Crawling + Indexing)</h3><p><em>Difficulty: Hard — asked at Google, Microsoft Bing, DuckDuckGo</em></p><h4>The Three Steps of Search</h4><pre>Step 1: CRAWLING  → Discover all web pages<br>Step 2: INDEXING  → Process pages, build searchable structure<br>Step 3: RANKING   → For a query, find and rank the best pages</pre><p>Step 1: Web Crawling</p><pre>┌─────────────────────────────────────────────────────────┐<br>│                    Web Crawler                            │<br>│                                                           │<br>│  URL Frontier ──► Fetch Page ──► Parse HTML              │<br>│  (Queue of        (HTTP GET)     Extract links          │<br>│   URLs to visit)                      │                  │<br>│       ▲                               │                  │<br>│       └───────────── Add new URLs ────┘                  │<br>│                                                           │<br>│  Robots.txt Check: &quot;Am I allowed to crawl this?&quot;        │<br>│  Politeness: &quot;Don&#39;t hit the same server more than       │<br>│               1 req/sec to avoid overloading it&quot;        │<br>│  Dedup: &quot;Have I seen this URL/content before?&quot;          │<br>└─────────────────────────────────────────────────────────┘</pre><p><strong>URL Frontier</strong> — A priority queue of URLs to crawl, sorted by priority:</p><ul><li>High priority: major news sites, Wikipedia</li><li>Low priority: obscure forums, static pages from 2003</li></ul><p><strong>Scale challenge:</strong> There are ~50 billion web pages. Crawling all of them requires thousands of crawler machines running continuously.</p><p><strong>Deduplication:</strong> The same content appears at different URLs (https://example.com and http://www.example.com/index.html). You need to detect this to avoid indexing duplicates.</p><p>Use <strong>simhash</strong> or <strong>MinHash</strong> to compute a fingerprint of each page’s content. If two pages have similar fingerprints, they are near-duplicates.</p><h4>Step 2: Indexing — Building the Inverted Index</h4><pre>BEFORE INDEXING (raw documents):<br>  Doc 1: &quot;The quick brown fox&quot;<br>  Doc 2: &quot;The brown fox jumps&quot;<br>  Doc 3: &quot;Quick brown dogs&quot;<br><br>AFTER INDEXING (inverted index):<br>  &quot;the&quot;   → [Doc1, Doc2]<br>  &quot;quick&quot; → [Doc1, Doc3]<br>  &quot;brown&quot; → [Doc1, Doc2, Doc3]<br>  &quot;fox&quot;   → [Doc1, Doc2]<br>  &quot;jumps&quot; → [Doc2]<br>  &quot;dogs&quot;  → [Doc3]<br><br>QUERY: &quot;brown fox&quot;<br>  Find &quot;brown&quot; → {Doc1, Doc2, Doc3}<br>  Find &quot;fox&quot;   → {Doc1, Doc2}<br>  Intersection → {Doc1, Doc2}<br>  → Return Doc1 and Doc2 (then rank them)</pre><p>The inverted index is the core data structure of every search engine. For the entire web, this index is terabytes in size and must be distributed across thousands of machines.</p><p><strong>Google’s approach — Distributed Indexing:</strong></p><ul><li>Index is sharded by document ID</li><li>Each shard stored on multiple machines for reliability</li><li>Queries are broadcast to all shards, partial results merged and ranked</li></ul><h4>Step 3: PageRank — Why It Changed Everything</h4><p>Before Google, search engines ranked pages by keyword frequency. Put “pizza pizza pizza pizza” in your page and you ranked for “pizza.”</p><p>PageRank had a simple but powerful insight: <strong>a page is important if important pages link to it.</strong></p><pre>Simple PageRank formula:<br>  PageRank(A) = sum of PageRank(B) / outlinks(B) for each page B that links to A<br><br>Intuition:<br>  If the New York Times (high PageRank) links to your page,<br>  your page gets more &quot;votes&quot; than if 10 random blogs link to it.<br><br>This models the web as a graph of trust/authority.<br>A vote from an authoritative site is worth more than votes from<br>low-quality sites.<br><br>Modern Google uses hundreds of signals beyond PageRank:<br>  - Content quality (grammar, readability, factual accuracy)<br>  - User signals (click-through rate, time on page)<br>  - Freshness (news articles decay faster than reference docs)<br>  - Mobile-friendliness<br>  - Page speed<br>  - Schema markup and structured data<br>  - E-E-A-T (Experience, Expertise, Authoritativeness, Trustworthiness)</pre><p>Search Architecture — Serving a Query</p><pre>User types: &quot;best system design books&quot;<br>                        │<br>                        ▼<br>               ┌────────────────┐<br>               │  Query Parsing │  ← Tokenize, stem, remove stopwords<br>               │  &quot;best&quot; →      │    &quot;best system design books&quot;<br>               │  &quot;system&quot; →    │    stem: &quot;design&quot; → &quot;design&quot;<br>               │  &quot;design&quot; →    │    remove: &quot;best&quot;?? No, keep it.<br>               │  &quot;books&quot; →     │<br>               └────────┬───────┘<br>                        │<br>                        ▼<br>               ┌────────────────┐<br>               │  Index Lookup  │  ← Broadcast to all index shards<br>               │  Find matching │<br>               │  documents     │<br>               └────────┬───────┘<br>                        │<br>                        ▼<br>               ┌────────────────┐<br>               │    Ranking     │  ← Apply PageRank + 200 other signals<br>               │  Top docs      │    for each candidate document<br>               └────────┬───────┘<br>                        │<br>                        ▼<br>               ┌────────────────┐<br>               │  Snippet       │  ← Generate preview text for each result<br>               │  Generation    │<br>               └────────┬───────┘<br>                        │<br>                        ▼<br>               Return top 10 results to user in &lt; 100ms</pre><p><strong>All of this happens in under 100 milliseconds.</strong> This is why Google has thousands of servers across dozens of data centers, all working in parallel.</p><h3>Block 12: Distributed System Concepts Every Senior Engineer Knows</h3><h4>Consistent Hashing (Deep Dive)</h4><p>We covered this in Part 2, but let us add the detail that separates a textbook answer from a production-grade one.</p><p><strong>The problem with virtual nodes:</strong></p><p>With basic consistent hashing, adding a server only takes load from the next server on the ring. The load is unevenly distributed — some servers get more range than others.</p><p><strong>Virtual nodes solve this:</strong></p><pre>Instead of placing each server once on the ring,<br>place it multiple times (100-200 virtual positions per server).<br><br>Physical Server A → Virtual nodes at positions 10, 45, 89, 134, ...<br>Physical Server B → Virtual nodes at positions 23, 67, 102, 178, ...<br>Physical Server C → Virtual nodes at positions 5, 56, 90, 156, ...<br><br>Each physical server gets ~1/N of the ring positions (on average).<br>This gives much more even load distribution.<br><br>When Server A is removed, its 100-200 virtual nodes are removed.<br>Load from those nodes distributes evenly across ALL remaining servers<br>(not just the next one).</pre><p>Amazon DynamoDB, Cassandra, and most production distributed databases use virtual nodes in their consistent hashing implementation.</p><h4>Leader Election — How Distributed Systems Agree on “Who’s in Charge”</h4><p>When you have 5 database nodes and the primary node dies, how do the remaining 4 agree on who becomes the new primary? If two nodes both think they are the leader, you get split-brain (two leaders, potential data corruption).</p><p><strong>Raft Consensus Algorithm (interview-friendly version):</strong></p><pre>3 possible states for each node: Leader, Follower, Candidate<br><br>Normal state:<br>  1 Leader, N Followers<br>  Leader sends heartbeats every 150ms to all Followers<br>  Followers reset their election timer on receiving heartbeat<br><br>Leader fails (no heartbeat received):<br>  Follower election timer expires (random 150-300ms)<br>  Becomes Candidate<br>  Sends &quot;vote for me&quot; to all other nodes<br>  If it gets majority votes (N/2 + 1) → becomes new Leader<br><br>Why random timer?<br>  Prevents two nodes from starting an election simultaneously<br>  (splitting the vote and causing a deadlock)<br><br>Split vote (rare):<br>  Two candidates get equal votes → election times out<br>  Random new timer → new election → one wins<br><br>Majority requirement:<br>  Need N/2 + 1 votes (majority) to prevent split-brain.<br>  In a 5-node cluster, need 3 votes.<br>  Two nodes can fail and the system still elects a leader.</pre><p><strong>Real-world use:</strong> etcd (used by Kubernetes), CockroachDB, TiDB all use Raft.</p><p><strong>Alternative:</strong> Paxos (more theoretically proven but harder to implement). ZooKeeper uses a Paxos variant called ZAB.</p><h4>Bloom Filters — Probabilistic Membership Testing</h4><p><strong>The problem:</strong> You have a database of 10 billion URLs (like Google has for web crawler dedup). For each URL the crawler sees, you need to check “have I already crawled this?” A hash lookup in a 10B-entry table is expensive.</p><p><strong>The solution:</strong> Bloom filter. — <a href="https://www.linkedin.com/posts/rahulv28_databasedesign-sqlvsnosql-databaseindexing-ugcPost-7307594389873156098-qeFX/?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAABVeNdoB5h8XdhyaqsDEGOmCkKDgxER10-0">Check this post</a></p><pre>A Bloom filter is a bit array of M bits (all starting at 0).<br>Uses K hash functions.<br><br>Adding &quot;https://google.com&quot;:<br>  hash1(&quot;https://google.com&quot;) % M = 42  → Set bit 42 = 1<br>  hash2(&quot;https://google.com&quot;) % M = 107 → Set bit 107 = 1<br>  hash3(&quot;https://google.com&quot;) % M = 891 → Set bit 891 = 1<br><br>Checking &quot;https://google.com&quot;:<br>  hash1() = 42  → bit 42 = 1? YES<br>  hash2() = 107 → bit 107 = 1? YES<br>  hash3() = 891 → bit 891 = 1? YES<br>  → &quot;Probably already seen&quot; (MIGHT be a false positive)<br><br>Checking &quot;https://unknown-site.com&quot;:<br>  hash1() = 44  → bit 44 = 0? NO<br>  → Definitely NOT seen before (NEVER a false negative)</pre><p><strong>Key property:</strong></p><ul><li><strong>False positives possible:</strong> Might say “seen” when it hasn’t.</li><li><strong>False negatives impossible:</strong> Never says “not seen” when it has.</li></ul><p>For web crawling, a false positive means occasionally skipping a URL. That is acceptable — the URL will be seen again later. A false negative would mean crawling the same URL twice — also manageable.</p><p>A Bloom filter for 10 billion URLs uses about 10GB of RAM (vs ~300GB for a hash set). This is why Google’s crawler uses Bloom filters.</p><p><strong>Other uses:</strong> Redis uses Bloom filters for cache membership checks. Databases use them to avoid querying disk if a key definitely does not exist.</p><h4>Distributed Transactions — The Hardest Problem</h4><p>When a transaction spans multiple services or databases, guaranteeing atomicity (all-or-nothing) is extremely hard.</p><p><strong>Example: Booking a flight + hotel</strong></p><ul><li>Debit credit card (Payment Service)</li><li>Reserve flight seat (Flight Service)</li><li>Reserve hotel room (Hotel Service)</li></ul><p>All three must succeed or all must roll back. If hotel is booked but payment fails, you owe a hotel room refund and a flight reservation cancellation.</p><p><strong>Two-Phase Commit (2PC):</strong></p><pre>Coordinator (e.g., Booking Service):<br>  Phase 1 - PREPARE:<br>    Send &quot;prepare&quot; to all participants<br>    Payment: &quot;Can you debit ₹50,000?&quot; → &quot;Ready&quot; (locks the money)<br>    Flight:   &quot;Can you reserve seat 14A?&quot; → &quot;Ready&quot; (locks the seat)<br>    Hotel:    &quot;Can you reserve room 203?&quot; → &quot;Ready&quot; (locks the room)<br><br>  Phase 2 - COMMIT (if all said Ready):<br>    Send &quot;commit&quot; to all<br>    Payment: deducts money<br>    Flight:   confirms reservation<br>    Hotel:    confirms reservation<br><br>  Phase 2 - ROLLBACK (if any said Not Ready):<br>    Send &quot;rollback&quot; to all<br>    Everyone releases their locks<br><br>PROBLEMS:<br>  - Blocking: If coordinator crashes after Phase 1, participants<br>    are stuck holding locks forever. The database is blocked.<br>  - Latency: Two round trips. Each participant holds locks during both phases.<br>  - Not truly fault tolerant.</pre><p>Saga Pattern (Modern Alternative):</p><pre>Break the transaction into local transactions + compensating transactions.<br><br>Booking Saga:<br>  Step 1: Debit payment → SUCCESS<br>  Step 2: Reserve flight → SUCCESS<br>  Step 3: Reserve hotel → FAILED (no rooms available)<br>  <br>  Trigger compensation (reverse order):<br>  Step 2 undo: Cancel flight reservation<br>  Step 1 undo: Refund payment<br><br>PROS:<br>  No distributed locks. No blocking. Each service owns its own transaction.<br>  Services are loosely coupled.<br><br>CONS:<br>  No atomicity — for brief moments, system is in inconsistent state.<br>  Compensating transactions are hard to design correctly.<br>  Need idempotency (running same compensation twice must be safe).<br><br>Used by: Amazon, Uber, Netflix for distributed workflows.</pre><h3>Block 13: Monitoring, Logging, and Reliability</h3><p>These topics are rarely taught but frequently asked about in senior interviews.</p><h4>The Four Golden Signals (Google SRE)</h4><p>Every production system must monitor these four metrics. If any of them degrades, something is wrong:</p><pre>1. LATENCY<br>   &quot;How long does it take to serve a request?&quot;<br>   Track both successful AND failed requests&#39; latency.<br>   Percentile matters more than average:<br>   p50 = median, p95 = 95th percentile, p99 = 99th percentile<br>   Average can lie. If 99% of requests are 1ms and 1% are 10,000ms,<br>   average is ~101ms — seems fine but 1% of users are suffering.<br><br>2. TRAFFIC<br>   &quot;How many requests per second?&quot;<br>   Know your baseline. If traffic suddenly drops 80%, you have an incident.<br>   If it spikes 500%, you might be getting DDoS&#39;d or something went viral.<br><br>3. ERRORS<br>   &quot;What fraction of requests are failing?&quot;<br>   Both explicit errors (HTTP 500) and implicit errors (HTTP 200 but wrong data).<br>   Set an alert if error rate exceeds 0.1%.<br><br>4. SATURATION<br>   &quot;How full is your system?&quot;<br>   CPU utilization, memory usage, disk space, queue depth.<br>   At what utilization does latency start to degrade?<br>   (Usually ~70% CPU is the threshold before latency climbs)</pre><h3>Circuit Breaker Pattern</h3><p>When Service A calls Service B, and Service B is slow/failing, requests from A pile up. Eventually A’s thread pool is exhausted, and A fails too. This is cascading failure — one service failure takes down all dependent services.</p><pre>CIRCUIT BREAKER - Three States:<br><br>┌─────────────────────────────────────────────────────────┐<br>│ CLOSED (normal operation):                               │<br>│   Requests flow normally.                                │<br>│   Track failure rate.                                    │<br>│   If &gt;50% failures in last 60s → OPEN                  │<br>└─────────────────────────────────────────────────────────┘<br>                           │ failure threshold exceeded<br>                           ▼<br>┌─────────────────────────────────────────────────────────┐<br>│ OPEN (blocking requests):                                │<br>│   Reject all requests immediately.                       │<br>│   Return error without calling downstream service.      │<br>│   After 30 seconds → HALF-OPEN                          │<br>└─────────────────────────────────────────────────────────┘<br>                           │ timeout elapsed<br>                           ▼<br>┌─────────────────────────────────────────────────────────┐<br>│ HALF-OPEN (testing recovery):                            │<br>│   Allow a few requests through.                          │<br>│   If they succeed → CLOSED (normal operation)            │<br>│   If they fail → OPEN again (back off more)              │<br>└─────────────────────────────────────────────────────────┘</pre><p><strong>Why this is important in interviews:</strong> When you design any system with service-to-service calls, always mention circuit breakers. It shows you think about failure modes, not just the happy path. Netflix’s Hystrix (now Resilience4j) is the famous implementation of this pattern.</p><h3>Design 9: Distributed Key-Value Store (Like DynamoDB)</h3><p><em>Difficulty: Hard — asked at Amazon, Google, Meta for senior/staff roles</em></p><p>This is not about using DynamoDB. It is about designing one from scratch. This question tests whether you understand the fundamentals of distributed systems.</p><h4>What does a key-value store need?</h4><ul><li>PUT(key, value) — Store a value</li><li>GET(key) → value — Retrieve a value</li><li>DELETE(key) — Remove a value</li></ul><p>Simple interface. Complex implementation.</p><h4>Core Design Decisions</h4><p><strong>Partitioning:</strong> How do you distribute keys across nodes? → Consistent hashing with virtual nodes (from Block 12).</p><p><strong>Replication:</strong> How many copies of each value? → Each key-value pair stored on N nodes (typically N=3). The next N nodes clockwise from the hash position on the ring.</p><p><strong>Consistency:</strong> When must all replicas agree? → Configurable! This is the key DynamoDB insight.</p><pre>Quorum-based consistency:<br>  N = total replicas<br>  W = number of writes that must succeed before returning &quot;success&quot;<br>  R = number of nodes that must respond to a read<br><br>  Strong consistency: W + R &gt; N (reads always see latest write)<br>    If N=3, W=2, R=2: W+R=4 &gt; 3 → Strong consistency<br>    <br>  Eventual consistency: W + R ≤ N<br>    If N=3, W=1, R=1: W+R=2 ≤ 3 → Eventually consistent<br>    (Fast but might return stale data)<br><br>  W=1, R=3 → Fast writes, strong reads (read all N=3 replicas, take latest)<br>  W=3, R=1 → Slow writes, fast reads<br><br>DynamoDB lets you choose: eventual or strong consistency per read request.</pre><p><strong>Conflict Resolution:</strong> What if two nodes have different values for the same key?</p><pre>Last Write Wins (LWW):<br>  Each write has a timestamp. Higher timestamp wins.<br>  PROBLEM: Clock skew. Two servers&#39; clocks might differ by milliseconds.<br>           The &quot;earlier&quot; write (by real time) might win.<br><br>Vector Clocks:<br>  Track causality: &quot;Write 2 happened after Write 1 on this node.&quot;<br>  Can detect truly concurrent writes (neither happened before the other).<br>  On conflict, return both values and let application decide.<br>  Used by Amazon Dynamo (the original research paper).<br><br>CRDTs (Conflict-free Replicated Data Types):<br>  Special data structures where concurrent edits always merge cleanly.<br>  Examples: Counters (both increments merge), sets (both additions merge).<br>  Cannot handle all data types, but where applicable, no conflicts possible.</pre><p><strong>Failure Detection:</strong> How does a node know another node is dead?</p><pre>Gossip Protocol:<br>  Each node periodically sends &quot;I&#39;m alive&quot; to K random neighbours.<br>  Those neighbours forward the message to K of their neighbours.<br>  <br>  Like gossip in an office — word spreads fast (O(log N) rounds)<br>  without a central coordinator.<br>  <br>  Node failure detection:<br>    If Node A hasn&#39;t heard from Node B in T seconds (via gossip),<br>    it marks B as potentially down.<br>    If multiple nodes mark B as down → B is considered failed.<br><br>Used by: Cassandra, AWS DynamoDB, Consul.</pre><p>Read and Write Path</p><pre>WRITE (PUT key=&quot;user:123&quot;, value=&quot;{name:Rahul}&quot;):<br><br>  Client ──► Any node (coordinator)<br>  Coordinator applies consistent hash → finds 3 replica nodes<br>  Coordinator sends write to 3 replicas in parallel<br>  Wait for W=2 replicas to acknowledge<br>  Return &quot;success&quot; to client<br>  Third replica acknowledges later (async)<br><br>READ (GET key=&quot;user:123&quot;):<br><br>  Client ──► Any node (coordinator)<br>  Coordinator applies consistent hash → finds 3 replica nodes<br>  Coordinator queries R=2 replicas in parallel<br>  Compare versions (vector clock) → return latest value<br>  If replicas disagree → read repair (update stale replica)</pre><p>Hinted Handoff — Handling Temporary Failures</p><pre>What if one replica is temporarily down during a write?<br><br>Without hinted handoff:<br>  Write to 3 replicas → One is down → Write to 2 → W=2 quorum met.<br>  Node comes back up → Missing the write → Data inconsistency forever.<br><br>With hinted handoff:<br>  Write to 3 replicas → One is down → Write to 2 replicas + 1 &quot;hint&quot;<br>  &quot;Hint&quot; = write stored on a healthy node with note: &quot;deliver to Node X when it recovers&quot;<br>  Node X recovers → Healthy node delivers the hinted write → Consistency restored.</pre><h3>The Complete Interview Strategy</h3><p>Now that you understand the concepts, here is how to actually perform in an interview.</p><h4>The First 5 Minutes Are Everything</h4><p>Most candidates fail by jumping into architecture immediately. The interviewer is testing your <em>process</em>, not just your knowledge.</p><pre>WRONG approach:<br>  Interviewer: &quot;Design Twitter.&quot;<br>  Candidate: &quot;Okay, so we have a load balancer, then some app servers,<br>              then a Cassandra cluster for tweets...&quot;<br><br>RIGHT approach:<br>  Interviewer: &quot;Design Twitter.&quot;<br>  Candidate: &quot;Great question. Before I start designing, I have a few<br>              clarifying questions...&quot;<br>              <br>  Question 1: &quot;What scale are we designing for? Twitter today<br>               (300M users) or Twitter at launch (100 users)?&quot;<br>  Question 2: &quot;What features are in scope? Just tweet creation and<br>               timeline? Or also search, DMs, trends?&quot;<br>  Question 3: &quot;What are the most critical non-functional requirements?<br>               Are we optimising for read latency, write throughput,<br>               or data consistency?&quot;<br>  Question 4: &quot;Any existing infrastructure or technical constraints<br>               I should know about?&quot;</pre><p>This shows maturity. Architects clarify requirements before designing.</p><h3>Back-of-Envelope: Always Show Your Math</h3><pre>After requirements, always do a quick estimate. Say it out loud.<br><br>&quot;Let me do a quick capacity estimate.<br> 300M monthly active users, say 100M daily active.<br> Each user creates 5 tweets/day → 500M tweets/day.<br> Tweets per second: 500M / 86,400 = ~5,800 tweets/second, call it 6K.<br> <br> Each tweet is ~280 characters + metadata, say 1KB.<br> Storage: 500M × 1KB = 500GB/day.<br> Over 5 years: 500GB × 365 × 5 = ~900TB of tweet data.<br> <br> Reads: 100M users each read 200 tweets/day = 20B reads/day.<br> Reads per second: 20B / 86,400 = ~230,000 reads/second. Peak 3x = 700K/sec.&quot;<br> <br>Knowing these numbers helps you justify:<br>  - Why you need database sharding (can&#39;t fit 900TB on one machine)<br>  - Why you need caching (700K reads/sec → can&#39;t hit DB for each)<br>  - Why you need CDN (media serving at scale)</pre><h3>How to Justify Every Design Choice</h3><p>Never just say “we use Redis here.” Always say:</p><p><strong>“We use Redis here because [reason], and not X because [trade-off].”</strong></p><p>Examples:</p><ul><li>“We use Redis for the session cache because it is an in-memory store with sub-millisecond reads. We could use Memcached but Redis has better support for data structures like sorted sets, which we need for leaderboards.”</li><li>“We use Cassandra for tweet storage because the access pattern is always by user_id and time range — a natural partition for Cassandra’s clustering keys. PostgreSQL could work at this scale but sharding it would be a significant operational burden.”</li><li>“We use consistent hashing for our cache layer because adding a new cache server only rebalances 1/N of the keys instead of all keys, which prevents a thundering herd when we scale.”</li></ul><h3>Common Follow-Up Questions and Perfect Answers</h3><p><strong>“What if your database goes down?”</strong> “We have Multi-AZ replication — a standby replica in a different Availability Zone. If the primary fails, we promote the replica. RTO (Recovery Time Objective) is under 30 seconds. We also have periodic backups to S3 for point-in-time recovery.”</p><p><strong>“How would you handle a 10x traffic spike?”</strong> “Three layers of defense: First, auto-scaling groups on our app servers spin up new instances in 2–3 minutes based on CPU thresholds. Second, our CDN absorbs most of the read load (static content, cached API responses). Third, our database read replicas handle the increased read load. If the spike is sustained, we cache aggressively at the application layer and consider read/write splitting.”</p><p><strong>“What’s your single biggest bottleneck?”</strong> Interviewers respect when you acknowledge weaknesses honestly. “Right now, the database write path is the bottleneck. We’re doing synchronous writes to the primary. If we need to scale writes 10x, we’d look at write buffering with Kafka, eventual consistency for some write paths, or sharding the database by user_id. Which direction should we explore?”</p><p><strong>“How do you ensure data doesn’t get lost?”</strong> “Three strategies. First, replication — every write goes to at least two replicas before acknowledging. Second, write-ahead logging — all database operations are written to a durable log before being applied. Third, regular backups to cold storage with tested restoration procedures. We also use checksums on data at rest to detect corruption.”</p><h3>The Cheat Sheet: What to Say When You Don’t Know</h3><p>Inevitably, an interviewer will probe something you are less certain about. Here is how to handle it gracefully:</p><p><strong>If you are uncertain about scale:</strong> “I’m not certain of the exact numbers, but let me reason about it. If I assume X, then…”</p><p><strong>If you don’t know a specific algorithm:</strong> “I’m not immediately familiar with the specific algorithm used here, but the properties we need are [correctness, performance, distributed]. Let me think about what class of solutions would meet those… [reason out loud].”</p><p><strong>If you draw a blank:</strong> “Let me take a step back and think about the core requirements for this piece. The key constraint is [X]. Given that constraint, the solution space narrows to…”</p><p>Interviewers value the ability to reason under uncertainty far more than having memorised every algorithm.</p><h3>The 10 Commandments of System Design Interviews</h3><ol><li><strong>Clarify before you draw.</strong> Ask at least 3 requirement questions before touching the whiteboard.</li><li><strong>Estimate before you design.</strong> Numbers justify architecture. Without them, your choices seem arbitrary.</li><li><strong>Always explain trade-offs.</strong> “We chose X, which gives us Y but costs us Z.”</li><li><strong>Think out loud.</strong> Interviewers want to see your reasoning, not just your conclusions.</li><li><strong>Design from client to database.</strong> Client → Load Balancer → Servers → Cache → Database → Storage.</li><li><strong>Handle failures explicitly.</strong> For every component, ask “what if this fails?” and answer it.</li><li><strong>Know the difference between read-heavy and write-heavy.</strong> The design changes significantly.</li><li><strong>Use the right tool.</strong> SQL for ACID, Cassandra for high-write time-series, Redis for cache, Kafka for async decoupling.</li><li><strong>Don’t over-engineer.</strong> A simple working system beats a theoretically perfect unmaintainable one. Start simple, evolve.</li><li><strong>Know your limits.</strong> If you don’t know something, say so and reason from first principles. Honesty + reasoning beats bluffing.</li></ol><h3>Your Study Plan (4 Weeks to Interview-Ready)</h3><p><strong>Week 1: Foundations</strong></p><ul><li>Read Part 1 of this series again. Draw every diagram from memory.</li><li>Practice explaining DNS, CDN, Load Balancer, Cache to a friend who is not in tech.</li><li>Design Rate Limiter and TinyURL on paper, without looking at notes.</li></ul><p><strong>Week 2: Core Systems</strong></p><ul><li>Read Part 2 again. Understand fan-out deeply.</li><li>Design Instagram, Twitter, WhatsApp on paper.</li><li>For each: write requirements, estimate capacity, draw architecture, explain 3 trade-offs.</li></ul><p><strong>Week 3: Advanced Concepts</strong></p><ul><li>Read Part 3. Focus on CAP, consistent hashing, Raft, Saga pattern.</li><li>Design YouTube and a distributed key-value store from scratch.</li><li>Pick one concept you are weakest on and go deep (read the original paper or a detailed blog).</li></ul><p><strong>Week 4: Practice</strong></p><ul><li>Do one timed mock interview per day (50 minutes, camera on, talk out loud).</li><li>Use a friend, Pramp, or interviewing.io.</li><li>After each mock: what did you say without evidence? What trade-offs did you forget? What would make your answer stronger?</li></ul><h3>Closing Thoughts</h3><p>System design is the skill that compounds most in engineering careers. Every senior engineer has designed systems under pressure, made the wrong call, learned from it, and refined their mental models.</p><p>This series covered the same material as the System Design Primer — one of the most valuable free engineering resources ever created — but with the additional layer of <em>why</em>, <em>what if removed</em>, and <em>what are the alternatives</em> that turns passive reading into genuine understanding.</p><p>The framework, the trade-offs, and the vocabulary you now have will serve you in interviews <em>and</em> in your actual job. When you are three years into a role and someone asks “should we use Kafka or RabbitMQ here?”, you will know that the real question is “do we need replay capability and multiple consumers, or is a simple task queue enough?”</p><p>That is the difference between someone who learned system design for an interview and someone who learned it for engineering.</p><p>Good luck.</p><p><em>This is Part 3 of a 3-part series. Read Part 1 (foundations + small systems) and Part 2 (medium systems) for the complete picture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec57fac32ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: From Zero to Google — Part 2]]></title>
            <link>https://medium.com/@rahul281191/system-design-from-zero-to-google-part-2-57c867fabefe?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/57c867fabefe</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 05:10:15 GMT</pubDate>
            <atom:updated>2026-08-04T05:10:15.512Z</atom:updated>
            <content:encoded><![CDATA[<h4>Medium-Scale Systems: Instagram, Twitter, WhatsApp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sAsYk4RNCFIBbOMGASL9w.png" /></figure><p><em>Part 1 covered the building blocks. Now we use all of them together to design real systems that handle millions of users. Each design introduces a new concept you’ll encounter in interviews at Google, Meta, and Amazon.</em></p><h4>Quick Recap from Part 1</h4><p>Before we dive in, the fundamentals you should have solid:</p><ul><li><strong>DNS</strong> → translates domain to IP</li><li><strong>CDN</strong> → serves static content from nearby servers</li><li><strong>Load Balancer</strong> → distributes traffic across servers</li><li><strong>Cache</strong> → Redis/Memcached for fast reads (check cache first, then DB)</li><li><strong>SQL vs NoSQL</strong> → ACID guarantees vs horizontal scale trade-off</li><li><strong>CAP Theorem</strong> → Consistency vs Availability during partition</li><li><strong>Replication</strong> → copies of data for availability and read scale</li></ul><p>Now let’s build real things.</p><h4>A Framework for Every System Design Interview</h4><p>Every interview, follow this structure. It signals seniority and prevents you from jumping into solutions before understanding the problem.</p><pre>Step 1: Clarify Requirements (3-5 minutes)<br>  - Functional: What must the system do?<br>  - Non-functional: Scale, latency, availability requirements?<br>  - Out of scope: What are we NOT building?<br><br>Step 2: Back-of-Envelope Estimates (2-3 minutes)<br>  - Daily active users, requests per second<br>  - Storage needed (now and in 5 years)<br>  - Read/write ratio (this determines caching strategy)<br><br>Step 3: High-Level Design (5-8 minutes)<br>  - Draw the big boxes: client, load balancer, servers, databases<br>  - Happy path end-to-end walkthrough<br><br>Step 4: Deep Dive — Key Components (10-15 minutes)<br>  - Data model (what tables/collections exist)<br>  - API design<br>  - Core algorithms<br>  - Justify every choice with trade-offs<br><br>Step 5: Scale and Edge Cases (5 minutes)<br>  - What breaks at 10x current scale?<br>  - Single points of failure?<br>  - What about hot users or hot content?</pre><p>Keep this structure in your head for every question.</p><h3>Design 4: Instagram — Photo Sharing at Scale</h3><p><em>Difficulty: Medium — common at Meta, Google, Amazon</em></p><h4>Understanding the System</h4><p>Instagram has two fundamentally different features that require different architectures:</p><ol><li><strong>Uploading a photo</strong> — write-heavy, latency can be slightly higher</li><li><strong>Viewing the feed</strong> — read-heavy, must be very fast (&lt; 100ms)</li></ol><p>This read/write asymmetry is the central design challenge.</p><h4>Requirements</h4><p><strong>Functional:</strong></p><ul><li>Users upload photos with captions</li><li>Users follow other users</li><li>Users see a feed of photos from people they follow</li><li>Users like and comment on photos</li></ul><p><strong>Non-functional (assume interview scale):</strong></p><ul><li>500 million daily active users</li><li>100 million photos uploaded per day</li><li>1 billion feed reads per day</li><li>Photo upload latency &lt; 2 seconds</li><li>Feed load latency &lt; 200ms</li><li>99.99% availability</li></ul><h4>Capacity Estimate</h4><pre>Photos uploaded:<br>  100M photos/day × 2MB average = 200TB/day of photo storage<br>  Over 5 years = 200TB × 365 × 5 = ~365PB<br><br>Reads:<br>  1 billion feed loads/day = ~11,500 reads/second (peak: 3x = ~35,000/sec)<br><br>Metadata:<br>  Each photo: user_id, url, timestamp, likes, caption = ~1KB<br>  100M photos/day × 1KB = 100GB/day of metadata</pre><h4>Photo Upload — The Write Path</h4><pre>User selects photo on phone<br>         │<br>         ▼<br>  Client compresses photo<br>  (reduce bandwidth)<br>         │<br>         ▼<br>┌────────────────┐<br>│   API Gateway   │ ← Authenticates user, rate limits<br>└───────┬────────┘<br>        │<br>        ▼<br>┌────────────────┐<br>│  Upload Service │ ← Generates unique photo ID (Snowflake)<br>└───────┬────────┘<br>        │<br>  ┌─────┴──────────────────────────┐<br>  │                                │<br>  ▼                                ▼<br>┌─────────────────┐      ┌─────────────────┐<br>│ Object Store    │      │  Photo Metadata  │<br>│ (S3/GCS)        │      │  Database        │<br>│                 │      │  (write photo_id │<br>│ Stores actual   │      │  url, user, etc) │<br>│ photo binary    │      └─────────────────┘<br>│                 │                │<br>└─────────────────┘                ▼<br>        │                ┌─────────────────┐<br>        │                │  Message Queue  │<br>        │                │  (Kafka)        │<br>        │                └───────┬─────────┘<br>        │                        │<br>        │                        ▼<br>        │               ┌─────────────────┐<br>        │               │ Async Workers   │<br>        │               │ - Resize image  │<br>        │               │ - Generate      │<br>        └──────────────►│   thumbnails    │<br>                        │ - Run ML models │<br>                        │ - Update feeds  │<br>                        └─────────────────┘</pre><h3>Why a Message Queue (Kafka) for Photo Processing?</h3><p>When a user uploads a photo, you need to:</p><ol><li>Store the original photo</li><li>Create thumbnail versions (100px, 400px, 1080px)</li><li>Run content moderation ML model</li><li>Push to followers’ feeds</li></ol><p>If you did all this synchronously (in the same request), the user would wait 10–30 seconds. Instead:</p><ol><li>Store the photo ✓</li><li>Return “Upload successful” to the user immediately</li><li>Put a message in Kafka: “Process photo ID 12345”</li><li>Workers consume from Kafka and handle processing asynchronously</li></ol><p><strong>If you removed the queue:</strong> Processing happens synchronously in the request. Users wait 30 seconds for uploads. One slow ML model brings down the upload service entirely (tight coupling). Workers cannot scale independently.</p><p><strong>Alternative to Kafka:</strong> AWS SQS (simpler, less features), RabbitMQ (better for task queues with acknowledgements), or simple database-backed job queues (sufficient for small scale).</p><h4>The Feed — The Read Path</h4><p>This is the interesting part. When Rahul opens Instagram, he sees a feed of photos from the 500 people he follows. How is this generated?</p><p><strong>Two approaches that every interviewer wants you to compare:</strong></p><p><strong>Approach 1: Fan-out on Write (Push Model)</strong></p><p>When Priya posts a photo, immediately push it to every follower’s feed inbox.</p><pre>Priya posts photo<br>        │<br>        ▼<br>  Kafka message<br>        │<br>        ▼<br>  Feed Service reads message<br>        │<br>        ▼<br>  For each of Priya&#39;s 200 followers:<br>    Redis: follower_feed:{user_id} → prepend photo_id<br>        │<br>        ▼<br>  When Rahul opens app:<br>    Read Rahul&#39;s pre-built feed from Redis → instant ✓</pre><pre>PROS:<br>✓ Feed reads are extremely fast (pre-computed, in Redis)<br>✓ Constant-time read: O(1) regardless of who you follow<br><br>CONS:<br>✗ &quot;Celebrity problem&quot;: Kylie Jenner has 400M followers<br>  One post → 400M writes to Redis (takes minutes)<br>✗ Storage: If you follow 500 people and they all post, your feed<br>  inbox is enormous<br>✗ Wasted work: posts from inactive users still get fanned out</pre><p><strong>Approach 2: Fan-out on Read (Pull Model)</strong></p><p>Don’t pre-build feeds. When Rahul opens the app, fetch posts from everyone he follows in real-time.</p><pre>Rahul opens app<br>        │<br>        ▼<br>  Feed Service:<br>    Get Rahul&#39;s following list (500 users)<br>        │<br>        ▼<br>    For each followed user, get their recent 10 posts<br>    (500 DB queries OR one query with IN clause)<br>        │<br>        ▼<br>    Sort all posts by timestamp<br>        │<br>        ▼<br>    Return top 20 posts as Rahul&#39;s feed</pre><pre>PROS:<br>✓ No fan-out storm for celebrities<br>✓ Always fresh data<br>✓ Less storage (no pre-built feeds)<br><br>CONS:<br>✗ Slow for users with many followings<br>  500 followees × 10 posts = 5,000 posts to fetch and sort on every load<br>✗ Database under heavy read load</pre><p><strong>The Production Solution: Hybrid</strong></p><p>This is what real systems (Twitter, Instagram) actually use:</p><pre>Regular users (&lt; 10,000 followers) → Fan-out on WRITE<br>  Small fan-out, fast operation.<br>  Their followers get pre-built feeds.<br><br>Celebrity accounts (&gt; 10,000 followers) → Fan-out on READ<br>  Too many followers to push to all.<br>  When a user opens their feed, posts from celebrities are<br>  fetched on-the-fly and merged with pre-built feed.<br><br>Why 10,000 as the threshold? At 10K followers, fan-out takes ~10ms.<br>At 400M followers (Kylie Jenner level), it would take hours.</pre><h4>The Social Graph — Following and Followers</h4><p>The “who follows whom” relationship is a classic graph problem.</p><p><strong>Storage:</strong></p><pre>For small scale:<br>  SQL Table:<br>  ┌────────────┬─────────────┐<br>  │ follower_id │ following_id │<br>  ├────────────┼─────────────┤<br>  │  u-1        │  u-2         │  &quot;User 1 follows User 2&quot;<br>  │  u-1        │  u-3         │  &quot;User 1 follows User 3&quot;<br>  └────────────┴─────────────┘<br>  Index on both columns.<br><br>For large scale (billions of edges):<br>  Graph database (Neo4j) or specialized graph storage<br>  OR<br>  Keep in SQL with aggressive caching<br>  (Instagram uses PostgreSQL + Redis cache for the follow graph)</pre><p><strong>Query patterns:</strong></p><ul><li>“Who follows User X?” → index on following_id</li><li>“Who does User X follow?” → index on follower_id</li><li>“Does User A follow User B?” → (A, B) composite index lookup</li></ul><h3>Design 5: Twitter Feed — The Fan-out Problem at Extreme Scale</h3><p><em>Difficulty: Medium-Hard — asked at Twitter, Meta, Google</em></p><h4>Why Twitter is Different from Instagram</h4><p>Twitter has a crucial distinction: <strong>tweet volume is enormous, and the celebrity problem is far more extreme.</strong> @BarackObama has 133M followers. A single tweet needs to reach 133M feeds.</p><p>In 2013, Twitter had a famous architectural debate when Beyoncé’s pregnancy announcement broke their system. Let us design our way past that.</p><h4>The Core Problem</h4><pre>Post tweet (100M tweets/day):<br>  ~1,150 tweets/second (peak ~5,000/second)<br><br>Read feed (300B feed reads/day):<br>  ~3.5M feed reads/second (peak ~10M/second)<br><br>That is a 3,000x read-to-write ratio.<br><br>If a celebrity with 100M followers tweets:<br>  Fan-out on write = 100M Redis updates<br>  At 100,000 Redis ops/second = 1,000 seconds = 16 minutes<br>  That is catastrophic.</pre><p><strong>Data Model</strong></p><pre>Users Table (SQL - PostgreSQL):<br>  user_id | handle  | name    | bio  | created_at<br>  ─────────────────────────────────────────────────<br>  1       | @rahul  | Rahul V | ...  | 2020-01-01<br><br>Tweets Table (SQL or wide-column - Cassandra):<br>  tweet_id | user_id | content | media_url | created_at | reply_to<br>  ──────────────────────────────────────────────────────────────────<br>  t123     | 1       | &quot;Hello&quot; | null      | 2024-01-01 | null<br><br>Follows Table (SQL or Graph DB):<br>  follower_id | following_id | created_at<br>  ──────────────────────────────────────────<br>  u2          | u1           | 2023-06-01  ← &quot;u2 follows u1&quot;<br><br>User Timeline Table (Redis or Cassandra - pre-built feeds):<br>  user_id | [tweet_ids in order] <br>  user:u2 | [t789, t456, t123, ...] ← pre-built timeline for u2</pre><p><strong>Architecture</strong></p><pre>┌─────────────────────────────────────────────────────┐<br>│                      Client App                      <br>└────────────────────────────┬────────────────────────┘<br>                             │<br>                    ┌────────▼────────┐<br>                    │   API Gateway   │<br>                    │  + Rate Limiter │<br>                    └────────┬────────┘<br>                ┌────────────┼────────────┐<br>                │            │            │<br>       ┌────────▼───┐  ┌─────▼─────┐  ┌──▼──────────┐<br>       │   Tweet    │  │  Timeline  │  │    User     │<br>       │  Service   │  │  Service   │  │   Service   │<br>       └────────┬───┘  └─────┬─────┘  └─────────────┘<br>                │            │<br>                ▼            ▼<br>         ┌──────────┐  ┌─────────────┐<br>         │ Cassandra │  │    Redis    │<br>         │ (tweets)  │  │ (timelines) │<br>         └──────────┘  └─────────────┘<br>                │<br>                ▼<br>         ┌──────────────┐<br>         │    Kafka     │  ← Fan-out happens asynchronously<br>         └──────┬───────┘<br>                │<br>         ┌──────▼───────┐<br>         │ Fan-out      │  ← Workers push tweets to follower timelines<br>         │  Workers     │<br>         └──────────────┘</pre><h4>Tweet Storage: Why Cassandra?</h4><p>Tweets have specific access patterns:</p><ul><li>Write once, read many times</li><li>Queries are almost always by user_id and time range (&quot;get @rahul&#39;s tweets from the last week&quot;)</li><li>No complex joins needed</li><li>Must handle billions of tweets with high write throughput</li></ul><p>Cassandra is a wide-column store where rows are partitioned by a key (e.g., user_id) and sorted by another key (e.g., tweet_id or created_at). This means &quot;get all tweets from user X sorted by time&quot; is a single, fast disk read.</p><pre>Cassandra partition key = user_id<br>Clustering key = tweet_id (descending, so newest first)<br><br>&quot;Get @rahul&#39;s last 20 tweets&quot; →<br>  SELECT * FROM tweets WHERE user_id = &#39;rahul&#39; LIMIT 20;<br>  → Single partition scan, extremely fast.</pre><p>If this were a SQL database with billions of rows, even with indexes, this query would hit multiple disk pages across many servers (random I/O). Cassandra makes it a sequential read on a single node.</p><h4>Fan-out Workers in Detail</h4><pre>Tweet posted by @rahul (who has 50,000 followers)<br>                    │<br>                    ▼<br>         Tweet saved to Cassandra<br>                    │<br>                    ▼<br>         Message pushed to Kafka topic: &quot;tweets&quot;<br>         Message: { tweet_id: t123, user_id: rahul, timestamp: ... }<br>                    │<br>                    ▼<br>┌─────────────────────────────────────────────────┐<br>│                  Fan-out Worker Pool             │<br>│                                                  │<br>│  Worker picks up message from Kafka              │<br>│                    │                             │<br>│  Fetch @rahul&#39;s follower list from DB: 50,000   │<br>│                    │                             │<br>│  Batch update Redis timelines:                   │<br>│  LPUSH user:timeline:{follower_id} tweet_id      │<br>│  LTRIM user:timeline:{follower_id} 0 999         │<br>│  (Keep only latest 1000 tweets per user in Redis)│<br>│                    │                             │<br>│  Done in ~5 seconds for 50,000 followers        │<br>└─────────────────────────────────────────────────┘</pre><h4>Handling Celebrities — The Special Case</h4><p>For accounts with more than 1 million followers, fan-out on write is too slow.</p><pre>When Rahul reads his feed:<br><br>1. Read pre-built timeline from Redis (regular accounts he follows)<br>   → [tweet_ids from regular accounts, already sorted]<br><br>2. For each celebrity he follows (&gt; 1M followers):<br>   → Fetch their latest tweets directly from Cassandra<br>   → These were NOT pre-built into his feed<br><br>3. Merge both lists by timestamp<br><br>4. Return top 20 tweets<br><br>This merge happens at read time, but it is cheap:<br>  - Only 5-10 celebrities per user on average<br>  - Cassandra query per celebrity: &lt; 5ms<br>  - Total merge: &lt; 20ms</pre><h4>Search: The Missing Piece</h4><p>Twitter also needs real-time search (“tweets mentioning #PulseBoard in the last hour”). This requires a different system entirely.</p><pre>Tweet created → Also indexed in Elasticsearch<br>  - Full-text search on content<br>  - Filter by timestamp, user, language<br>  - Returns results in milliseconds<br><br>Why Elasticsearch and not Cassandra?<br>  Cassandra is fast for known partition keys. Searching by<br>  text content across all tweets requires inverted indexes —<br>  a data structure Cassandra does not have.<br>  Elasticsearch (Lucene underneath) is built for text search.</pre><h3>Block 9: Message Queues — Decoupling Services</h3><p>Before designing the chat app, we need to deeply understand message queues because they appear in nearly every large-scale system.</p><h4>What is a message queue?</h4><p>A queue where a <strong>producer</strong> puts messages and a <strong>consumer</strong> reads them. If the consumer is slow or down, messages wait in the queue. The producer does not know or care about the consumer.</p><pre>SYNCHRONOUS (without queue):<br>  Service A ──HTTP call──► Service B<br>  Service A waits for B to respond.<br>  If B is slow: A is slow.<br>  If B crashes: A fails.<br>  If B cannot keep up with A: A is blocked.<br><br>ASYNCHRONOUS (with queue):<br>  Service A ──message──► [Queue] ──message──► Service B<br>  Service A sends message and continues immediately.<br>  If B is slow: Messages queue up, A is unaffected.<br>  If B crashes: Messages wait, none are lost, B processes when it recovers.<br>  If B cannot keep up: Queue grows, add more B workers.</pre><h4>Kafka vs RabbitMQ</h4><p>These are the two most commonly discussed in interviews:</p><pre>                    KAFKA                    RABBITMQ<br>─────────────────────────────────────────────────────────<br>Type           Message Stream              Message Queue<br>Model          Log-based (append-only)     Queue (consume-delete)<br>Retention      Messages kept for 7 days    Messages deleted after ack<br>Replay         Yes, consumers can          No, once consumed it&#39;s gone<br>               re-read old messages<br><br>Throughput     Millions/sec                Hundreds of thousands/sec<br>Use Case       Event streaming, logs,      Task queues, email sending,<br>               analytics, audit trails     notifications, job processing<br><br>Consumer       Multiple independent        Only ONE consumer group<br>model          consumer groups can         reads each message<br>               read same data<br><br>Order          Guaranteed within           Guaranteed within queue<br>               a partition<br><br>CHOOSE KAFKA WHEN:<br>  - You need replay (reprocess historical data)<br>  - Multiple services need same event (audit + analytics + ML)<br>  - Very high throughput (IoT, clickstream)<br>  - Event sourcing patterns<br><br>CHOOSE RABBITMQ WHEN:<br>  - Simple task queue (send email, process order)<br>  - Each task done by exactly one worker<br>  - Complex routing rules between exchanges<br>  - When Kafka is overkill</pre><p><strong>Simple memory model for interviews:</strong></p><ul><li>Kafka = a newspaper. Many people can read the same edition. Old editions are archived.</li><li>RabbitMQ = a post office. Each letter goes to exactly one recipient. Once delivered, it is gone.</li></ul><h3>Design 6: WhatsApp / Chat Application</h3><p><em>Difficulty: Medium-Hard — extremely common at all top companies</em></p><h4>Why chat is different from everything else</h4><p>In all previous designs, the client <em>pulled</em> data from the server (user opens app → request → server → response). Chat is different: <strong>the server must push messages to the client the moment they arrive.</strong> You cannot ask “do I have new messages?” every second — it is too slow and wastes battery.</p><h4>The WebSocket breakthrough</h4><p>HTTP is request-response. The client sends a request, the server responds, connection closes. There is no way for the server to spontaneously send data to the client.</p><p><strong>WebSocket</strong> is a different protocol that upgrades an HTTP connection to a persistent, bidirectional TCP connection.</p><pre>Regular HTTP:<br>  Client: &quot;Any new messages?&quot;  → Server: &quot;No.&quot;<br>  Client: &quot;Any new messages?&quot;  → Server: &quot;No.&quot;<br>  Client: &quot;Any new messages?&quot;  → Server: &quot;No.&quot;<br>  Client: &quot;Any new messages?&quot;  → Server: &quot;Yes! Here it is!&quot;<br>  (This is called polling. Wastes bandwidth. Still has delay.)<br><br>WebSocket:<br>  Client: &quot;Open connection&quot;    → Server: &quot;Connection open&quot;<br>  [Connection stays open]<br>  Server: &quot;You have a message!&quot; → Client receives immediately<br>  Client: &quot;Sending a message&quot;   → Server receives immediately<br>  [Persistent, bidirectional]</pre><p>Each user is connected to ONE chat server. The server maintains an in-memory mapping: user_id → WebSocket connection object</p><h4>Sending a Message — Walkthrough</h4><p>Rahul (on Server 3) sends “Hello” to Priya (on Server 7):</p><pre>Step 1: Rahul types &quot;Hello&quot; and hits send.<br>         Message goes to Server 3 via WebSocket.<br><br>Step 2: Server 3 looks up: &quot;Which server is Priya on?&quot;<br>         → Asks Redis: GET user_server:priya → &quot;Server 7&quot;<br><br>Step 3: Server 3 sends message to Server 7<br>         (Server-to-server HTTP call or internal message queue)<br><br>Step 4: Server 7 looks up Priya&#39;s WebSocket connection<br>         → Pushes &quot;Hello&quot; to Priya in real-time<br><br>Step 5: Message stored in database (for history, offline delivery)<br><br>Step 6: Delivery receipt sent back to Rahul:<br>         Double tick (✓✓) = delivered<br><br>Step 7: When Priya reads the message:<br>         Read receipt sent back to Rahul:<br>         Blue double tick (✓✓) = read</pre><p>Diagram</p><pre>┌──────────┐     ┌──────────────┐     ┌──────────────┐     ┌──────────┐<br>│  Rahul   │     │  Chat        │     │  Chat        │     │  Priya   │<br>│  (phone) │     │  Server 3    │     │  Server 7    │     │  (phone) │<br>└────┬─────┘     └──────┬───────┘     └──────┬───────┘     └────┬─────┘<br>     │WebSocket  │                            │                  │WebSocket<br>     │           │   1. Message arrives       │                  │<br>     │──&quot;Hello&quot;─►│                            │                  │<br>     │           │   2. Lookup Priya&#39;s server │                  │<br>     │           │───────GET user_server:─────►│                  │<br>     │           │       priya → Server7      │                  │<br>     │           │                            │                  │<br>     │           │   3. Forward to Server 7   │                  │<br>     │           │──────────&quot;Hello&quot;──────────►│                  │<br>     │           │                            │   4. Push to    │<br>     │           │                            │──────Priya──────►│<br>     │           │                            │                  │<br>     │           │   5. Save to DB            │                  │<br>     │           │────────────────────────────────────────────── │<br>     │           │            Message DB (Cassandra)             │<br>     │           │                            │                  │<br>     │ ◄─&quot;delivered&quot;────────────────────────── │                  │</pre><p>Message Storage — Cassandra Again</p><pre>Cassandra Schema for messages:<br>  Partition key: conversation_id<br>  Clustering key: message_id (descending = newest first)<br><br>  conversation_id | message_id | sender_id | content | timestamp | type<br>  chat:u1:u2     | msg_999    | u1        | &quot;Hello&quot; | 2024-01   | text<br>  chat:u1:u2     | msg_998    | u2        | &quot;Hi!&quot;   | 2024-01   | text<br><br>Query: &quot;Give me last 50 messages between Rahul and Priya&quot;<br>  → SELECT * FROM messages WHERE conversation_id = &#39;chat:rahul:priya&#39;<br>    ORDER BY message_id DESC LIMIT 50;<br>  → Single partition read. Extremely fast.</pre><p>Why Cassandra here (same reasoning as Twitter tweets)?</p><ul><li>Write-heavy (billions of messages per day)</li><li>Read pattern is always by conversation_id (natural partition key)</li><li>No complex queries needed</li><li>Needs to scale across many nodes with high availability</li></ul><h4>Offline Message Delivery</h4><p>When Priya’s phone is off, the message must be delivered when she comes back online.</p><pre>Priya is offline:<br>  Server 7 tries to push to Priya&#39;s WebSocket<br>  Connection is gone → Push fails<br>  → Store message in &quot;pending delivery&quot; queue in Redis/DB<br><br>Priya comes back online:<br>  Phone reconnects via WebSocket to any Chat Server (say Server 2)<br>  Server 2: Registers Priya → Server 2 mapping in Redis<br>  Server 2: Checks pending queue for Priya<br>  → Delivers all pending messages in order<br>  → Priya sees messages she missed</pre><h4>Group Chats</h4><p>In group chats, one message goes to many recipients. This is exactly the fan-out problem from Twitter!</p><p><strong>For small groups (&lt; 100 members):</strong> Fan-out immediately. When message arrives, push to all members’ servers simultaneously.</p><p><strong>For large groups (up to 10,000 like WhatsApp):</strong> Store the message once, have each group member’s server fetch it when they connect.</p><pre>Small group message:<br>  Message arrives at Server 3<br>  → Fetch all 10 group members and their servers<br>  → Push to each member&#39;s server in parallel<br>  → All 10 see it within milliseconds<br><br>Large group (1,000 members):<br>  Message arrives and is stored with conversation_id<br>  → Message fanned out asynchronously via Kafka<br>  → Each member gets notified and fetches the message<br>  → Slightly slower but avoids overwhelming servers with 1,000 simultaneous pushes</pre><h3>Block 10: Database Sharding</h3><p>Sharding is splitting a database across multiple machines. It is essential for databases that exceed what a single server can hold or handle.</p><h4>Why sharding?</h4><p>Even the biggest single database server (say 64TB of storage, 2TB RAM) eventually fills up or becomes too slow. Instagram has petabytes of photo metadata. Twitter has billions of tweets. No single machine can hold all of this.</p><h4>Horizontal vs Vertical Partitioning</h4><pre>VERTICAL PARTITIONING (split by column):<br>  Split one table into multiple tables, each with fewer columns.<br>  <br>  Original: users(user_id, name, email, bio, profile_pic, settings)<br>  <br>  After vertical partition:<br>  users_basic(user_id, name, email)  ← frequently accessed<br>  users_profile(user_id, bio, profile_pic, settings)  ← less frequent<br>  <br>  Good when you have many columns and only some are hot.<br>  Tables can be on different machines.<br><br>HORIZONTAL PARTITIONING = SHARDING (split by row):<br>  Distribute rows across multiple database instances.<br>  <br>  users_shard_1: user_ids 1 - 1,000,000<br>  users_shard_2: user_ids 1,000,001 - 2,000,000<br>  users_shard_3: user_ids 2,000,001 - 3,000,000</pre><h4>Sharding Strategies</h4><p><strong>Range-Based Sharding:</strong></p><pre>Shard 1: user_id 1 to 1M<br>Shard 2: user_id 1M to 2M<br>Shard 3: user_id 2M to 3M<br><br>PROBLEM: Hotspots. Most new users get high IDs, so Shard 3<br>is always the hot shard while Shard 1 is idle.</pre><p><strong>Hash-Based Sharding:</strong></p><pre>shard = hash(user_id) % number_of_shards<br><br>user_id 123 → hash(123) % 4 = 3 → Shard 3<br>user_id 456 → hash(456) % 4 = 0 → Shard 0<br>user_id 789 → hash(789) % 4 = 1 → Shard 1<br><br>PROS: Even distribution, no hotspots.<br>PROBLEM: Adding a new shard requires resharding everything.<br>  Old: hash(user_id) % 4<br>  New: hash(user_id) % 5<br>  Almost every user moves to a different shard!</pre><h4>Consistent Hashing (The Industry Standard):</h4><pre>Imagine a ring from 0 to 2^32.<br>Place shard servers at positions on the ring.<br>Map each data item to a position (hash(key)).<br>Data is stored on the first shard clockwise from its position.<br><br>Ring:  0 ────► Shard A (pos 100) ────► Shard B (pos 200) ────► Shard C (pos 300) ──► 0<br><br>user_id 150 → mapped to position 150 → stored on Shard B (first clockwise shard)<br>user_id 250 → mapped to position 250 → stored on Shard C<br><br>ADDING A NEW SHARD D at position 250:<br>  Only data between pos 200 and 250 moves from Shard C to Shard D.<br>  Everything else stays the same!<br><br>This is why consistent hashing is critical: adding/removing nodes<br>only moves ~1/N of the data instead of everything.</pre><h4>The Problems with Sharding</h4><p>Sharding solves the scale problem but introduces new headaches:</p><p><strong>Cross-shard joins:</strong> If user data is on Shard 1 and order data is on Shard 2, a SQL JOIN between them is impossible without application-level joining (slow and complex).</p><p><strong>Cross-shard transactions:</strong> Making a payment that spans two shards requires distributed transactions (two-phase commit) which are slow and error-prone.</p><p><strong>Hotspot shards:</strong> A celebrity user with billions of followers causes disproportionate load on their shard.</p><p><strong>Solution for hotspot:</strong> Shard by (user_id, date) so even a single user&#39;s data spreads across multiple shards over time.</p><h3>Block 11: Microservices vs Monolith</h3><p>This is not just about architecture — it is about team size, deployment speed, and system complexity.</p><h4>Monolith</h4><p>One deployable unit. Everything in one codebase.</p><pre>┌─────────────────────────────────────┐<br>│          Single Application         │<br>│                                     │<br>│  [User Module] [Post Module]        │<br>│  [Feed Module] [Notification Module]│<br>│  [Search Module] [Payments Module]  │<br>│                                     │<br>│  All share the same database.       │<br>│  Deploy everything together.        │<br>└─────────────────────────────────────┘</pre><p><strong>Good:</strong></p><ul><li>Simple to develop (one repo, one deployment)</li><li>No network latency between components</li><li>Easy to test end-to-end</li><li>No distributed systems complexity</li></ul><p><strong>Bad:</strong></p><ul><li>One team’s buggy code breaks everything</li><li>Cannot scale components independently (Feed needs 100 servers, Payments needs 2)</li><li>Deployment risk grows with team size</li><li>Technology lock-in (everything must use same language/framework)</li></ul><p><strong>Use when:</strong> Small team (&lt; 20 engineers), early stage, moving fast.</p><h4>Microservices</h4><p>Multiple independent services, each owning its data, deployed independently.</p><pre>┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐<br>│  User    │  │  Post    │  │  Feed    │  │Notification<br>│ Service  │  │ Service  │  │ Service  │  │  Service │<br>│  (own DB)│  │  (own DB)│  │  (Redis) │  │  (own DB)│<br>└──────────┘  └──────────┘  └──────────┘  └──────────┘<br>      │             │             │               │<br>      └─────────────┴─────────────┴───────────────┘<br>                         │<br>                  ┌──────▼──────┐<br>                  │ API Gateway │ ← Single entry point for clients<br>                  └─────────────┘</pre><p><strong>Good:</strong></p><ul><li>Independent deployment (Feed team deploys without affecting Payments)</li><li>Independent scaling (spin up 100 Feed servers, keep 2 Payments servers)</li><li>Technology choice per service</li><li>Failure isolation (Payment service down → Feed still works)</li></ul><p><strong>Bad:</strong></p><ul><li>Network latency between services</li><li>Distributed tracing is hard (follow one request across 10 services)</li><li>Data consistency is hard (no single database transaction across services)</li><li>Operational complexity (service discovery, load balancing per service)</li><li>Much harder to test end-to-end</li></ul><p><strong>Use when:</strong> Large team (50+ engineers), mature product, independent scaling needs.</p><p><strong>The honest advice:</strong> Most systems start as a monolith and extract services as specific scaling or team structure demands it. Microservices-first is often premature optimisation.</p><h3>Part 3 Preview</h3><p>In Part 3, we tackle the hardest systems:</p><ul><li><strong>YouTube</strong> — video encoding pipeline, CDN strategy, recommendation system</li><li><strong>Google Search</strong> — web crawling, indexing, PageRank</li><li><strong>Distributed Databases</strong> — how to build something like DynamoDB from scratch</li><li><strong>Full interview strategy</strong> — how to approach any system design question you’ve never seen before</li></ul><p><em>Follow for Part 3. Comment below: which system design from Part 2 would you struggle most with in an actual interview?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57c867fabefe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: From Zero to Google — Part 1]]></title>
            <link>https://medium.com/@rahul281191/system-design-from-zero-to-google-part-1-6447711f9909?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/6447711f9909</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 12:43:42 GMT</pubDate>
            <atom:updated>2026-08-03T12:43:42.759Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Foundation Every Engineer Needs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAQfwC2VzmY0HmRsyhyaiQ.png" /></figure><p><em>If you can read this article and draw a diagram for every concept, you are ready for your first system design round. No fluff, no theory dumps — just the real building blocks with honest “why” and “what if I removed it” answers.</em></p><p>This three-part series covers <strong>everything</strong> in the System Design Primer.</p><p><strong>Part 1</strong> covers the foundations and small-system designs (Rate Limiter, TinyURL, Pastebin). <strong>Part 2</strong> covers medium-scale systems (Instagram, Twitter Feed, Chat App). <strong>Part 3</strong> covers large-scale systems (YouTube, Google Search, Distributed Databases).</p><p>Start here. Read in order. By the end you will not just memorise answers — you will understand <em>why</em> every piece exists.</p><h4>The One Rule of System Design</h4><p>Before touching a single concept, burn this into your memory:</p><blockquote><strong><em>Everything in system design is a trade-off. There is no single right answer — only the most appropriate answer for the given constraints.</em></strong></blockquote><p>The interviewer is not testing whether you know the perfect architecture. They are testing whether you can <em>reason</em> about trade-offs, explain why you chose something, and explain what you would lose if you chose differently.</p><h4>How a Request Actually Travels (The Big Picture First)</h4><p>You type google.com in your browser. Here is <em>everything</em> that happens before you see results:</p><pre>┌─────────────┐<br>│   Browser   │  ← You type &quot;google.com&quot;<br>└──────┬──────┘<br>       │ 1. DNS Lookup — &quot;What is the IP for google.com?&quot;<br>       ▼<br>┌─────────────┐<br>│  DNS Server │  ← Returns: 142.250.190.14<br>└──────┬──────┘<br>       │ 2. HTTP Request to that IP<br>       ▼<br>┌─────────────┐<br>│     CDN     │  ← Serves static files (images, JS, CSS) from nearby server<br>└──────┬──────┘<br>       │ 3. Dynamic request forwarded to origin<br>       ▼<br>┌─────────────┐<br>│ Load Balancer│ ← Distributes request to one of many servers<br>└──────┬──────┘<br>       │<br>       ▼<br>┌─────────────┐    ┌─────────────┐<br>│  App Server │    │  App Server │  ← One of these handles your request<br>└──────┬──────┘    └─────────────┘<br>       │<br>       ▼<br>┌─────────────┐    ┌─────────────┐<br>│    Cache    │ OR │  Database   │  ← Data comes from fast cache or slower DB<br>└─────────────┘    └─────────────┘</pre><p>Each block in this diagram is a concept you need to understand. Let us go through them one by one.</p><h3>Block 1: DNS — The Internet’s Phone Book</h3><h4>What is it?</h4><p>DNS (Domain Name System) translates human-readable names like google.com into machine-readable IP addresses like 142.250.190.14. Your browser cannot connect to google.com directly — it needs an IP address.</p><h4>Why does this block exist?</h4><p>IP addresses change. Servers get replaced. If your browser hardcoded 142.250.190.14, it would break the moment Google moved their server. DNS lets Google change their IP address without you changing anything.</p><h4>What happens step by step?</h4><pre>Your browser asks: &quot;What is the IP for google.com?&quot;<br><br>Step 1: Check browser cache (fastest, milliseconds)<br>        ↓ Not there?<br>Step 2: Check your OS cache / hosts file<br>        ↓ Not there?<br>Step 3: Ask your ISP&#39;s Recursive Resolver<br>        ↓ Not there?<br>Step 4: Ask Root Name Server → &quot;Try .com servers&quot;<br>Step 5: Ask .com Name Server → &quot;Try google.com&#39;s servers&quot;<br>Step 6: Ask Google&#39;s Authoritative Name Server → Gets the real IP<br>Step 7: Returns IP, caches it with a TTL (Time To Live)</pre><h4>What is TTL?</h4><p>TTL is the expiry time on a DNS record. If Google sets TTL to 300 seconds (5 minutes), your browser reuses the cached IP for 5 minutes and then asks again.</p><p><strong>Low TTL</strong> = slower (more DNS queries) but flexible (can change IP quickly). <strong>High TTL</strong> = faster (fewer queries) but inflexible (takes long to propagate changes).</p><h4>What if you removed DNS?</h4><p>Every website would need a fixed IP address. You would have to type 142.250.190.14 instead of google.com. The internet would be unusable for humans.</p><h4>Alternative?</h4><p>/etc/hosts file is a primitive alternative — you manually map domain names to IPs. Used for local development (localhost) and by malware to redirect traffic.</p><h3>Block 2: CDN — Your Content’s Nearest Neighbour</h3><h4>What is it?</h4><p>A Content Delivery Network is a globally distributed network of servers. When a user in Mumbai requests your website, instead of the request going all the way to your server in New York (high latency), it is served by a CDN server in Mumbai (low latency).</p><h4>Real-world example</h4><p>Netflix uses Akamai and their own Open Connect CDN. When you watch a video, it is not streaming from a Netflix data center in California — it is streaming from a server that may literally be inside your ISP’s building.</p><h4>What does a CDN serve?</h4><ul><li>Static files: images, videos, CSS, JavaScript, fonts</li><li>Some CDNs (like CloudFront) also handle dynamic content</li></ul><h4>Two types of CDN</h4><pre>PUSH CDN                              PULL CDN<br>─────────────────────────────────────────────────────────<br>You upload files to CDN manually.    CDN fetches from your<br>                                      server on first request.<br><br>Good for:                             Good for:<br>- Content that rarely changes         - Content that changes often<br>- Small sites where you control       - High traffic sites<br>  exactly what gets cached            - When you don&#39;t want to<br>                                       manage uploads<br><br>Example: You upload your app&#39;s        Example: Twitter profile pics —<br>logo.png to CDN once.                 CDN fetches once, caches.</pre><h4>What if you removed CDN?</h4><p>Every request goes to your origin server. A user in Tokyo gets 200ms round-trip latency to your New York server instead of 5ms to a local CDN node. For video streaming, this would be unwatchable. Your origin server also takes all the load — it would need to be massively bigger.</p><h4>Why not always use CDN?</h4><p>CDN costs money. For a startup with 100 users, the origin server is fine. CDNs make sense when your users are geographically distributed and you serve lots of static content.</p><h3>Block 3: Load Balancer — The Traffic Director</h3><h4>What is it?</h4><p>A load balancer sits in front of multiple servers and routes incoming requests to one of them. It prevents any single server from being overwhelmed.</p><pre>WITHOUT LOAD BALANCER:<br>User 1 ─────┐<br>User 2 ──── │──► Server A (overloaded, crashes)<br>User 3 ─────┘<br><br><br>WITH LOAD BALANCER:<br>User 1 ─────┐<br>User 2 ──── │──► Load Balancer ──► Server A<br>User 3 ─────┘                   ├──► Server B<br>                                 └──► Server C</pre><h4>Load balancing algorithms</h4><p><strong>Round Robin</strong> — Distribute requests in order: A, B, C, A, B, C…</p><ul><li>Simple. Works when all servers have equal capacity.</li><li>Problem: Doesn’t account for server load. Server A might be handling a slow database query while getting new requests.</li></ul><p><strong>Least Connections</strong> — Send to server with fewest active connections.</p><ul><li>Better for long-lived connections (WebSockets, video streaming).</li></ul><p><strong>IP Hash</strong> — Hash the user’s IP to always route them to the same server.</p><ul><li>Used when you need session stickiness (same user, same server).</li><li>Problem: If one IP sends tons of requests (DDoS), that server gets hammered.</li></ul><p><strong>Weighted Round Robin</strong> — Give more requests to more powerful servers.</p><p><strong>Layer 4 vs Layer 7 Load Balancing</strong></p><pre>Layer 4 (Transport Layer):<br>- Routes based on IP and TCP/UDP port only.<br>- Cannot read the actual HTTP request content.<br>- Faster (less processing).<br>- Example: Routing all TCP port 443 traffic to server pool.<br><br>Layer 7 (Application Layer):<br>- Reads the actual HTTP request.<br>- Can route based on URL, headers, cookies.<br>- Smarter but slightly slower.<br>- Example: Route /api/video/* to video servers,<br>           /api/search/* to search servers.</pre><h4>What if you removed the load balancer?</h4><p>One server handles all traffic. When it crashes, your entire service goes down. You cannot scale horizontally (adding more servers does nothing if there’s no way to route to them).</p><h4>Alternative?</h4><p>DNS-based load balancing — multiple IP addresses for the same domain, round-robin at DNS level. Simpler but dumber: DNS cannot detect if a server is down.</p><h4>Load Balancer trade-offs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-fEV_FW-_XYoveaJMfhhA.png" /></figure><h3>Block 4: Horizontal vs Vertical Scaling</h3><h4>Vertical Scaling (Scale Up)</h4><p>Make your single server bigger — more RAM, faster CPU, larger disk.</p><pre>Before: [🖥️ 4 cores, 8GB RAM]<br>After:  [🖥️ 32 cores, 256GB RAM]</pre><p><strong>Good:</strong> Simple. No application changes needed. No distributed system complexity. <strong>Bad:</strong> Has a hard ceiling (no single machine can have unlimited RAM). Expensive at high end. Single point of failure.</p><h4>Horizontal Scaling (Scale Out)</h4><p>Add more servers.</p><pre>Before: [Server A]<br>After:  [Server A] [Server B] [Server C] [Server D]</pre><p><strong>Good:</strong> Theoretically unlimited. Commodity hardware (cheap). High availability. <strong>Bad:</strong> Requires load balancer. Servers must be stateless (sessions cannot live on one server). More complex.</p><h4>The stateless server requirement</h4><p>For horizontal scaling to work, every server must be able to handle any request. This means:</p><ul><li><strong>No local session storage</strong> — If user logs in on Server A, Server B should also know they’re logged in.</li><li><strong>Solution:</strong> Store sessions in a shared cache like Redis or a database.</li></ul><pre>BAD (Stateful servers):<br>User logs in → Server A stores session in memory<br>Next request → Goes to Server B → &quot;Who are you?&quot;<br><br>GOOD (Stateless servers):<br>User logs in → Session stored in Redis<br>Next request → Goes to Server B → Reads session from Redis → ✓</pre><h3>Block 5: Caching — The Speed Cheat Code</h3><h4>What is it?</h4><p>Store the result of an expensive operation (a slow database query, a complex calculation, an API call) in fast memory so future requests get it instantly.</p><h4>The simple mental model</h4><p>Think of it like post-it notes on your desk. Instead of walking to the filing cabinet (database) every time someone asks for a report, you keep the most recent report on a post-it. Much faster. But the post-it can become outdated.</p><h4>Cache patterns explained simply</h4><p><strong>Cache-Aside (Lazy Loading)</strong></p><pre>Request comes in:<br>  ↓<br>Check cache → HIT? Return cached value.<br>  ↓ MISS<br>Query database → Get result<br>  ↓<br>Store in cache → Return result<br><br>PROS: Only caches what&#39;s actually requested. Cache failure doesn&#39;t break the app.<br>CONS: First request is always slow (cache miss). Data can be stale.</pre><p><strong>Write-Through</strong></p><pre>Write request comes in:<br>  ↓<br>Write to CACHE first → Write to DATABASE<br>  ↓<br>Return success<br><br>PROS: Cache is always up to date. Never stale.<br>CONS: Every write hits the cache (even data that&#39;s never read). Slow writes.</pre><p><strong>Write-Behind (Write-Back)</strong></p><pre>Write request comes in:<br>  ↓<br>Write to CACHE → Return success immediately<br>  ↓ (asynchronously, later)<br>Write to DATABASE<br><br>PROS: Very fast writes.<br>CONS: Data loss risk if cache fails before writing to DB. Complex.</pre><h4>Cache eviction policies</h4><p>When the cache is full and a new item needs to be stored, what do you remove?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkXRq4SWx2OQNxpALopSGw.png" /></figure><h4>What if you removed the cache?</h4><p>Every request hits the database. A database can handle maybe 10,000 queries per second under ideal conditions. A cache like Redis can handle 1,000,000+ operations per second. Without cache, your service either dies under load or requires a massive (expensive) database cluster.</p><h4>Real-world example: Facebook</h4><p>Facebook caches billions of items in Memcached. When you view a profile, it checks the cache first. The database is only hit for the initial load or when the cache expires. This is why Facebook loads so fast even though your profile data has to travel from their servers.</p><h3>Block 6: Databases — SQL vs NoSQL</h3><p>This is one of the most common interview questions, and most people answer it wrong by saying “NoSQL is faster” or “SQL is more reliable.” That is a oversimplification that will lose you points with a senior interviewer.</p><h4>The honest answer</h4><p><strong>Both can be fast. Both can be slow. The real question is: what guarantees do you need?</strong></p><h4>SQL (Relational Databases)</h4><p>Examples: PostgreSQL, MySQL, SQLite</p><p><strong>ACID Guarantees:</strong></p><pre>A — Atomicity:   Either all parts of a transaction succeed, or none do.<br>                 (Transfer ₹1000: debit + credit either both happen or neither)<br><br>C — Consistency: Database moves from one valid state to another.<br>                 (You can&#39;t have negative bank balance)<br><br>I — Isolation:   Concurrent transactions don&#39;t interfere with each other.<br>                 (Two people buying last item — only one succeeds)<br><br>D — Durability:  Once committed, data survives crashes.<br>                 (Your payment confirmation is permanent)</pre><p><strong>When to use SQL:</strong></p><ul><li>Financial data (you cannot afford to lose a transaction)</li><li>Relational data (users have orders, orders have items — JOINs are natural)</li><li>Complex queries (reporting, analytics, aggregations)</li><li>You need strong consistency (read reflects the most recent write)</li></ul><p><strong>Example:</strong> Banking system. If Priya sends ₹10,000 to Rahul, you need the debit and credit to <em>both</em> happen or <em>neither</em> happen. ACID guarantees this. NoSQL typically does not.</p><h4>NoSQL (Non-Relational Databases)</h4><p><strong>BASE properties (opposite of ACID):</strong></p><pre>BA — Basically Available:  System stays available even if some nodes fail<br>S  — Soft state:          Data might be in flux (not guaranteed to be latest)<br>E  — Eventually Consistent: All nodes will agree on the value... eventually</pre><p>Types of NoSQL:</p><pre>Key-Value Store (Redis, DynamoDB):<br>  user:123 → { name: &quot;Rahul&quot;, role: &quot;admin&quot; }<br>  Fast reads/writes. No querying by value.<br>  Use for: Sessions, caches, shopping carts.<br><br>Document Store (MongoDB, Firestore):<br>  { _id: &quot;123&quot;, name: &quot;Rahul&quot;, orders: [{ id: &quot;o1&quot;, amount: 500 }] }<br>  Flexible schema. Query inside documents.<br>  Use for: User profiles, catalogs, CMS.<br><br>Wide-Column Store (Cassandra, HBase):<br>  Rows have dynamic columns. Rows partitioned across nodes.<br>  Massive scale, optimized for writes.<br>  Use for: IoT data, time-series, logs.<br><br>Graph Database (Neo4j):<br>  Nodes and edges. &quot;Find friends of friends who live in Bangalore.&quot;<br>  Use for: Social networks, fraud detection, recommendations.</pre><p><strong>Why does NoSQL scale more easily?</strong></p><p>Not because of magic. Because of <em>relaxed consistency guarantees</em>. If you don’t need every node to agree instantly, you can shard data across hundreds of machines with no coordination overhead. SQL’s ACID guarantees require coordination (locking, two-phase commit) which becomes expensive at global scale.</p><h4>The real decision matrix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i382vTifCx9xFrEZ70cMTw.png" /></figure><h3>Block 7: CAP Theorem — The Fundamental Limit</h3><p>This theorem proves that in a distributed system (multiple servers), you can <strong>only guarantee 2 of these 3 properties at any one time</strong>:</p><pre>       CONSISTENCY<br>            /\<br>           /  \<br>          /    \<br>         /      \<br>        /  PICK  \<br>       /   TWO   \<br>      /____________\<br>AVAILABILITY    PARTITION<br>                TOLERANCE</pre><p><strong>Consistency</strong> — Every read gets the most recent write. No stale data. <strong>Availability</strong> — Every request gets a response (not necessarily the latest data). <strong>Partition Tolerance</strong> — System keeps working even if some servers cannot talk to each other (network failures).</p><p><strong>The key insight:</strong> In real distributed systems, network failures (partitions) <em>will</em> happen. You cannot opt out of Partition Tolerance — it will be forced on you by reality. So the real choice is:</p><pre>CP (Consistency + Partition Tolerance):<br>  When network fails → Reject requests rather than return stale data.<br>  Examples: Banking systems, HBase, Zookeeper.<br>  User experience: &quot;Service temporarily unavailable&quot;<br><br>AP (Availability + Partition Tolerance):<br>  When network fails → Return possibly stale data rather than reject.<br>  Examples: DynamoDB, Cassandra, CouchDB.<br>  User experience: &quot;Might show slightly old data&quot;</pre><p><strong>Simple example:</strong> Two database nodes, Node A and Node B, lose connection to each other.</p><ul><li><strong>CP system:</strong> Both nodes stop accepting writes (prevent inconsistency). Your bank balance is safe but you cannot make transactions.</li><li><strong>AP system:</strong> Both nodes accept writes. When connection restores, they reconcile. Your “likes” count might be slightly off for a moment.</li></ul><p><strong>The “CA” myth:</strong> Many textbooks claim you can have Consistency + Availability. This only holds when there are <em>no</em> network partitions — which is impossible to guarantee in the real world.</p><h3>Block 8: Availability Patterns</h3><h4>How to measure availability</h4><p>Availability is measured in “nines”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zP41_GjsQMIKibcIuJG5PQ.png" /></figure><p>Google SRE aims for four nines. AWS S3 guarantees 11 nines for durability (that is how many nines of probability your data won’t be lost).</p><h4>Failover patterns</h4><p><strong>Active-Passive (Hot Standby)</strong></p><pre>Traffic ──► [Primary Server] ──► (does the work)<br>                │<br>                │ heartbeat<br>                ▼<br>           [Standby Server] ──► Takes over if Primary dies<br><br>PRO: Simple, proven.<br>CON: Standby server wastes resources while idle.<br>CON: Brief downtime during switchover (seconds to minutes).</pre><p><strong>Active-Active</strong></p><pre>Traffic ──► [Load Balancer]<br>               │       │<br>               ▼       ▼<br>          [Server A] [Server B]  ← Both handle traffic simultaneously<br>               │       │<br>               └───┬───┘<br>                   ▼<br>             [Shared DB]<br><br>PRO: Zero downtime if one server dies. Better resource utilization.<br>CON: Sessions must be shared (stateless design needed). More complex.</pre><h4>Replication</h4><p><strong>Master-Slave (Primary-Replica):</strong></p><pre>Client writes → [Primary DB] → replicates to → [Replica 1] → [Replica 2]<br>                                               <br>Client reads → any replica<br><br>Good for: Read-heavy workloads (Instagram feeds, product pages).<br>Problem: If Primary dies, replica must be promoted (brief downtime).<br>          Replica data might lag behind Primary by milliseconds.</pre><p><strong>Master-Master:</strong></p><pre>[DB Node 1] ←──sync──► [DB Node 2]<br>Both accept writes, both replicate to each other.<br><br>Good for: High availability, geographically distributed writes.<br>Problem: Conflict resolution is hard. What if both nodes update the same<br>         row simultaneously with different values?</pre><h3>Now Let’s Design Real Systems</h3><p>With these building blocks understood, let’s design three complete systems from scratch.</p><h3>Design 1: Rate Limiter</h3><p><em>Difficulty: Small — asked at all company levels</em></p><h4>What is a rate limiter?</h4><p>A rate limiter restricts how many requests a client (user or IP) can make in a given time window. Without it, one malicious or buggy client can bring down your entire service.</p><p><strong>Real examples:</strong></p><ul><li>Twitter API: 300 tweets per 15 minutes</li><li>GitHub API: 5,000 requests per hour</li><li>OTP systems: 3 attempts per phone number per hour</li></ul><h4>Requirements clarification (always do this first in an interview)</h4><p><strong>Functional:</strong></p><ul><li>Given a request, return whether it should be allowed or rejected</li><li>Support rate limiting per user, per IP, or per API endpoint</li><li>Return HTTP 429 “Too Many Requests” when rate exceeded</li></ul><p><strong>Non-functional:</strong></p><ul><li>Low latency (rate check adds &lt; 1ms to request)</li><li>Highly available (if the rate limiter goes down, what happens?)</li><li>Accurate (doesn’t let through too many or reject too few)</li></ul><h4>Capacity estimate</h4><p>If we have 10 million users, and each user makes 10 requests/minute:</p><ul><li>100 million checks/minute</li><li>~1.67 million checks/second</li><li>Each counter needs ~20 bytes of storage</li><li>10 million users × 20 bytes = 200MB (fits in Redis easily)</li></ul><h4>Algorithms — the heart of rate limiting</h4><p><strong>Token Bucket Algorithm (Most Common)</strong></p><pre>Imagine a bucket that holds 10 tokens.<br>Tokens refill at rate: 1 token per second.<br>Each request costs 1 token.<br><br>Timeline:<br>Second 0:  Bucket = [🪙🪙🪙🪙🪙🪙🪙🪙🪙🪙]  (10 tokens)<br>Second 0:  10 requests arrive → Use 10 tokens → ALLOWED<br>Second 0:  1 more request → No tokens → REJECTED ❌<br>Second 1:  1 token added → Bucket = [🪙]<br>Second 1:  1 request → Use 1 token → ALLOWED ✓<br><br>PROS: Allows bursting (user can use 10 tokens immediately).<br>CONS: Need to track timestamp of last refill per user.<br>USE FOR: APIs where occasional bursts are acceptable.</pre><p><strong>Fixed Window Counter</strong></p><pre>Divide time into fixed windows (e.g., 1-minute buckets).<br>Count requests in current window.<br><br>12:00:00 - 12:00:59 → User A: 5 requests ✓<br>12:00:00 - 12:00:59 → User A: 5 more requests ✓ (limit = 10)<br>12:00:00 - 12:00:59 → User A: 1 more request ❌ (over limit)<br>12:01:00            → New window, counter resets<br>12:01:00            → User A: 10 more requests ✓<br><br>PROBLEM: The &quot;boundary burst&quot; attack:<br>  - User sends 10 requests at 12:00:59 (last second of window)<br>  - Sends 10 more at 12:01:00 (first second of new window)<br>  - Gets 20 requests in 2 seconds instead of 10 allowed.</pre><h4>Sliding Window Log</h4><pre>Keep a log of timestamps of each request.<br>On new request: remove entries older than window size.<br>If remaining count &lt; limit → allow.<br><br>12:00:00 User A requests: log = [12:00:00]             Count: 1<br>12:00:30 User A requests: log = [12:00:00, 12:00:30]   Count: 2<br>12:01:05 User A requests:<br>  Remove entries before 12:00:05 → log = [12:00:30, 12:01:05] Count: 2<br><br>PROS: Very accurate. No boundary burst problem.<br>CONS: Stores every request timestamp. High memory for heavy users.</pre><p><strong>Sliding Window Counter (Best Balance)</strong></p><pre>Hybrid: Use two counters (current window + previous window).<br>Weight previous window by how much time has elapsed.<br><br>Current rate = prev_count × (1 - elapsed/window) + curr_count<br><br>Example (window = 60 seconds):<br>  30 seconds into current minute:<br>  Previous minute: 8 requests<br>  Current minute: 3 requests<br>  <br>  Rate = 8 × (1 - 30/60) + 3 = 8 × 0.5 + 3 = 7 requests (approximate)<br>  <br>PROS: Low memory. Good approximation of sliding window.<br>CONS: Not perfectly accurate (estimate).<br>USE FOR: Production systems. Used by Cloudflare.</pre><h4>System design — the full diagram</h4><pre>Client Request<br>     │<br>     ▼<br>┌─────────────────┐<br>│   API Gateway   │  ← All requests enter here<br>│  (Rate Limiter) │<br>└────────┬────────┘<br>         │<br>         ▼ Check rate limit<br>┌─────────────────┐<br>│   Redis Cache   │  ← Stores counters per user/IP<br>│  user:123 → 47  │  ← &quot;User 123 made 47 requests this minute&quot;<br>└────────┬────────┘<br>         │<br>    ┌────┴────┐<br>    ▼         ▼<br> Allowed   Rejected<br>    │         │<br>    ▼         ▼<br>Backend   HTTP 429<br> Server   Response<br>    │<br>    ▼<br> Process<br> Request</pre><h4>Why Redis for storing counters?</h4><ul><li><strong>Speed:</strong> Redis is an in-memory store. Reading/writing a counter takes &lt; 0.1ms.</li><li><strong>Atomic operations:</strong> Redis INCR command increments a counter atomically — no race conditions where two servers both read &quot;47&quot; and both write &quot;48&quot; when the correct answer is &quot;49&quot;.</li><li><strong>TTL support:</strong> Redis keys can auto-expire. Perfect for “reset counter after 60 seconds.”</li><li><strong>Alternative:</strong> Memcached. Simpler but lacks atomic increment and persistence.</li></ul><h4>What if the rate limiter goes down?</h4><p><strong>Fail open:</strong> Allow all requests through. Service stays up but can be abused. <strong>Fail closed:</strong> Reject all requests. Service is protected but completely unavailable.</p><p>Most production systems <strong>fail open</strong> because keeping the service alive is more important than rate limiting during a brief outage.</p><h4>What if you have multiple servers?</h4><p>Each server needs to talk to the same Redis instance (centralized) or you get inconsistency: Server A thinks the user made 5 requests, Server B thinks 3, actual total is 8.</p><p>For global rate limiting at massive scale: Use Redis Cluster across regions, with slight consistency trade-off (acceptable — a few extra requests getting through is better than the latency of cross-region coordination).</p><h3>Design 2: TinyURL — URL Shortener</h3><p><em>Difficulty: Small-Medium — extremely common interview question</em></p><h4>Why does TinyURL exist?</h4><p>Long URLs are ugly and break in SMS/email. https://www.amazon.in/dp/B09G3HRMVB/ref=sr_1_3?keywords=keyboard becomes tinyurl.com/2abc4xy. Every link shortener solves the same core problem: long URL in, short URL out, click takes you to the original.</p><h4>The deceptive simplicity</h4><p>It looks like two database operations. But at scale (billions of links, trillions of redirects), every design choice matters.</p><h4>Requirements</h4><p><strong>Functional:</strong></p><ol><li>Given a long URL, return a short URL (e.g., tinyurl.com/abc123)</li><li>Given a short URL, redirect to the original long URL</li><li>Optional: Custom aliases, expiry dates, analytics</li></ol><p><strong>Non-functional:</strong></p><ul><li>Read-heavy: 100:1 read-to-write ratio (people click way more than they create)</li><li>Low latency for redirects (&lt; 10ms is ideal)</li><li>High availability (link must always resolve)</li></ul><h4>Capacity estimate (back-of-envelope — always do this)</h4><ul><li>100 million new URLs created per day</li><li>10 billion redirects per day</li><li>Each URL stored as ~500 bytes</li><li>Storage per day = 100M × 500B = 50GB/day</li><li>Storage for 5 years = 50GB × 365 × 5 = ~90TB</li></ul><h4>The Core Problem: Generating Short Codes</h4><p><strong>Option 1: Random Hash (MD5/SHA-256 + truncate)</strong></p><pre>Input: https://www.example.com/very/long/url<br>MD5 hash: a665a45920422f9d417e4867efdc4fb8<br>Take first 7 characters: a665a45<br><br>Short URL: tinyurl.com/a665a45<br><br>PROBLEM: Hash collisions. Two different long URLs could produce the<br>same 7-character hash. Probability is low but non-zero at scale.<br>Solution: Check database, if collision, take next 7 characters.<br><br>PROS: Simple, no central coordinator needed.<br>CONS: Collision handling adds latency. 7 chars gives 16^7 = ~268M combos.</pre><p><strong>Option 2: Auto-increment ID + Base62 Encoding</strong></p><pre>Each URL stored with auto-incrementing ID.<br>Convert ID to Base62 (a-z, A-Z, 0-9).<br><br>ID 1   → &quot;1&quot;<br>ID 62  → &quot;10&quot; (Base62)<br>ID 100 → &quot;1c&quot; (Base62)<br><br>Example:<br>  ID = 123456789<br>  Base62 = &quot;8M0kX&quot;  (7 characters)<br>  Short URL: tinyurl.com/8M0kX<br><br>PROS: No collisions guaranteed. Short codes (7 chars = 62^7 = 3.5 trillion combos).<br>CONS: Requires a central ID generator. IDs are predictable (security concern).<br>      If 3 servers are generating IDs, they can conflict.</pre><p><strong>Option 3: Snowflake ID (Industry standard for distributed systems)</strong></p><pre>A 64-bit ID composed of:<br> ┌──────────────┬───────────┬──────────────┬───────────────┐<br> │ Timestamp    │ Datacenter│  Machine ID  │   Sequence    │<br> │  41 bits     │  5 bits   │   5 bits     │   12 bits     │<br> └──────────────┴───────────┴──────────────┴───────────────┘<br><br>- Globally unique without coordination between servers<br>- Timestamp-ordered<br>- 4096 unique IDs per millisecond per machine<br><br>Use this in production. It is what Twitter, Discord, and most<br>large services use for unique ID generation.</pre><p><strong>Full system architecture</strong></p><pre>                         ┌──────────────────┐<br>                         │   Client Browser │<br>                         └────────┬─────────┘<br>                                  │<br>                         ┌────────▼─────────┐<br>                         │   Load Balancer  │<br>                         └────────┬─────────┘<br>                    ┌─────────────┴─────────────┐<br>                    │                           │<br>           ┌────────▼────────┐       ┌──────────▼────────┐<br>           │  Write Service  │       │   Read Service     │<br>           │ (Create URLs)   │       │ (Redirect URLs)    │<br>           └────────┬────────┘       └──────────┬─────────┘<br>                    │                           │<br>         ┌──────────▼────────┐     ┌────────────▼──────────┐<br>         │   ID Generator    │     │    Redis Cache         │<br>         │   (Snowflake)     │     │  short → long URL      │<br>         └──────────┬────────┘     │  Cache hit → redirect  │<br>                    │              │  Cache miss → DB query  │<br>                    │              └────────────┬────────────┘<br>                    │                           │<br>         ┌──────────▼───────────────────────────▼────────────┐<br>         │                  Database                          │<br>         │   id | short_code | long_url | created_at | ttl    │<br>         │    1 |   abc123   | https://...  | 2024-01  | NULL  │<br>         └────────────────────────────────────────────────────┘</pre><h4>Database choice: SQL or NoSQL?</h4><p><strong>For TinyURL, NoSQL (Cassandra or DynamoDB) is the better choice.</strong> Here is why:</p><p>The primary access pattern is a simple key-value lookup: short_code → long_url. There are no complex queries, no joins, no aggregations. This is exactly what key-value stores excel at.</p><p>At 10 billion redirects/day (~115,000 reads/second), you need to shard the data across many machines. Cassandra is designed for this — data is distributed by partition key (short_code) with consistent hashing.</p><p><strong>If you chose SQL:</strong> You would need extensive sharding (horizontal partitioning), which is complex to implement in MySQL/PostgreSQL and not their natural strength. But SQL is fine for small-scale (millions, not billions of URLs).</p><h4>The redirect: 301 vs 302</h4><p>When someone clicks a short URL, your server needs to redirect them. There are two HTTP status codes:</p><pre>301 Permanent Redirect:<br>  &quot;This URL has permanently moved to the long URL.&quot;<br>  Browser caches this redirect forever.<br>  Future clicks → Browser goes directly to long URL (never hits your server).<br>  PROS: Reduces load on your server.<br>  CONS: You lose analytics. Browser won&#39;t ask you again.<br><br>302 Temporary Redirect:<br>  &quot;This URL is temporarily at the long URL for now.&quot;<br>  Browser does NOT cache this. Every click hits your server.<br>  PROS: You can track analytics. Can change the destination.<br>  CONS: Higher load on your server.<br><br>For analytics (know who clicked, when, from where) → Use 302.<br>For pure performance and CDN efficiency → Use 301.<br>TinyURL uses 301. Bit.ly uses 302 (for analytics).</pre><h4>Cache strategy for reads</h4><p>Since reads vastly outnumber writes, cache the short → long mapping in Redis.</p><ul><li>On redirect request: Check Redis first (&lt; 1ms).</li><li>Cache hit: Return immediately. Database is never touched.</li><li>Cache miss: Query database, store result in Redis with TTL, return.</li></ul><p>At 115,000 reads/second with 99% cache hit rate, the database only handles 1,150 queries/second — very manageable.</p><p><strong>Cache eviction:</strong> Use LRU (Least Recently Used). Old, unpopular links are evicted. Hot links stay warm.</p><h4>Summary: Part 1</h4><p>You have now learned the foundation of system design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLMaqMS3n-a6kC9aWDiHuw.png" /></figure><h4>Part 2 Preview</h4><p>In Part 2, we design medium-scale systems:</p><ul><li><strong>Instagram</strong> — photo storage, feed generation, follow graph</li><li><strong>Twitter Feed</strong> — the famous fan-out problem (Kylie Jenner problem)</li><li><strong>WhatsApp/Chat App</strong> — WebSockets, message ordering, offline delivery</li></ul><p>Each will use these building blocks, and you will see how they combine differently depending on the system’s unique requirements.</p><p><em>If this helped you, follow for Part 2. Drop a comment with which concept was clearest and which needs more explanation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6447711f9909" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React + JavaScript Machine Coding Handbook]]></title>
            <link>https://medium.com/@rahul281191/react-javascript-machine-coding-handbook-adf1d2b1a962?source=rss-bbaf34695b86------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf1d2b1a962</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[machine-coding-round]]></category>
            <dc:creator><![CDATA[Rahul Verma]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 05:25:36 GMT</pubDate>
            <atom:updated>2026-08-20T05:57:07.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0adEoTx-g2oiC6uoT7OGzA.png" /></figure><p>Based on my interview history (Microsoft, ServiceNow, Mercari, Calix, etc.), I would build this specifically for <strong>Senior Frontend (4–8 years)</strong>, not beginner React.</p><h4>CHAPTER 1 — API Patterns</h4><p><strong>What interviewers are testing</strong></p><p>When they say:</p><blockquote><em>Fetch data from this API and display it.</em></blockquote><p>They’re <strong>not</strong> testing if you know fetch(). They&#39;re testing if you know:</p><ul><li>API calls</li><li>React hooks</li><li>State management</li><li>Error handling</li><li>Loading state</li><li>Data transformation</li><li>Performance</li><li>Component design</li></ul><p>A senior developer thinks beyond “getting data.”</p><h4>Pattern 1 — Basic Fetch API</h4><h4>Interview Question</h4><blockquote><em>Fetch users from an API and display them.</em></blockquote><pre>Component Mount<br>      │<br>      ▼<br>useEffect()<br>      │<br>      ▼<br>Call API<br>      │<br>      ▼<br>Loading = true<br>      │<br>      ▼<br>Response received<br>      │<br>      ▼<br>Store in state<br>      │<br>      ▼<br>Loading = false<br>      │<br>      ▼<br>Render UI</pre><pre>const [users, setUsers] = useState([]);<br>const [loading, setLoading] = useState(false);<br>const [error, setError] = useState(null);<br><br>// users stores data<br>// show sppinner<br>// show errors</pre><h4>Step 2 — API Function</h4><p>Never write API inside JSX.</p><p>Create a function.</p><pre>const fetchUsers = async () =&gt; {<br>    try {<br>        setLoading(true);<br><br>        const response = await fetch(<br>            &quot;https://jsonplaceholder.typicode.com/users&quot;<br>        );<br><br>        if (!response.ok) {<br>            throw new Error(&quot;Failed&quot;);<br>        }<br><br>        const data = await response.json();<br><br>        setUsers(data);<br>    } catch (err) {<br>        setError(err.message);<br>    } finally {<br>        setLoading(false);<br>    }<br>};</pre><p>Why finally?</p><p>What if an error occurs before setLoading(false)?</p><p>Spinner never stops.</p><h4>Step 3 — useEffect</h4><pre>useEffect(() =&gt; {<br>    fetchUsers();<br>}, []);</pre><p>Why empty dependency?</p><pre>Only once<br><br>// without it<br><br>Render<br><br>↓<br><br>API<br><br>↓<br><br>State update<br><br>↓<br><br>Render<br><br>↓<br><br>API<br><br>↓<br><br>Infinite Loop</pre><p>Step 4 — Render</p><pre>if (loading) {<br>    return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>}<br><br>if (error) {<br>    return &lt;h2&gt;{error}&lt;/h2&gt;;<br>}<br><br>return (<br>    &lt;div&gt;<br>        {users.map(user =&gt; (<br>            &lt;p key={user.id}&gt;<br>                {user.name}<br>            &lt;/p&gt;<br>        ))}<br>    &lt;/div&gt;<br>);</pre><h4>Interviewer Follow-up 1</h4><h4>“What if the API has 10,000 users?”</h4><p>Don’t render everything.</p><p>Use</p><pre>Virtualization</pre><h4>Interviewer Follow-up 2</h4><h4>“Can the user retry?”</h4><p>Add a button.</p><pre>&lt;button onClick={fetchUsers}&gt;<br>    Retry<br>&lt;/button&gt;</pre><h4>Interviewer Follow-up 3</h4><h4>“Can you refresh data?”</h4><pre>&lt;button onClick={fetchUsers}&gt;<br>    Refresh<br>&lt;/button&gt;</pre><h4>Interviewer Follow-up 4</h4><h4>“What if the component unmounts before the API returns?”</h4><p>This is a <strong>very common senior interview question</strong>.</p><p>Example</p><pre>Open page<br><br>↓<br><br>API starts<br><br>↓<br><br>Navigate away<br><br>↓<br><br>API finishes<br><br>↓<br><br>setUsers()<br><br>↓<br><br>Component already removed</pre><p>React may warn about updating state after unmount (depending on the React version and scenario), and the request is unnecessary.</p><p>The senior solution is to <strong>cancel the request</strong>.</p><h4>Pattern 2 — AbortController</h4><pre>useEffect(() =&gt; {<br><br>    const controller = new AbortController();<br><br>    const fetchUsers = async () =&gt; {<br><br>        try {<br><br>            const response = await fetch(url, {<br>                signal: controller.signal<br>            });<br><br>            const data = await response.json();<br><br>            setUsers(data);<br><br>        } catch (err) {<br><br>            if (err.name !== &quot;AbortError&quot;) {<br>                setError(err.message);<br>            }<br>        }<br>    };<br><br>    fetchUsers();<br><br>    return () =&gt; {<br>        controller.abort();<br>    };<br><br>}, []);</pre><h4>Pattern 3 — API Retry</h4><p>Imagine</p><pre>Internet disconnected</pre><pre>const fetchUsers = async (retry = 3) =&gt; {<br><br>    try {<br><br>        const response = await fetch(url);<br><br>        return await response.json();<br><br>    } catch (err) {<br><br>        if (retry &gt; 0) {<br>            return fetchUsers(retry - 1);<br>        }<br><br>        throw err;<br>    }<br><br>};</pre><h4>Pattern 5 — Polling</h4><p>Interview</p><blockquote><em>Refresh every 5 seconds.</em></blockquote><pre>useEffect(() =&gt; {<br><br>    fetchUsers();<br><br>    const interval = setInterval(() =&gt; {<br>        fetchUsers();<br>    }, 5000);<br><br>    return () =&gt; clearInterval(interval);<br><br>}, []);</pre><h4>Pattern 6 — Parallel APIs</h4><p>Interview</p><pre>Users<br><br>Posts<br><br>Albums<br><br>Load together</pre><p>Don’t do:</p><pre>await fetchUsers();<br><br>await fetchPosts();<br><br>await fetchAlbums();</pre><p>Instead:</p><pre>const [users, posts, albums] =<br>await Promise.all([<br>    fetchUsers(),<br>    fetchPosts(),<br>    fetchAlbums()<br>]);</pre><p>Much faster because the requests run simultaneously.</p><h4>Pattern 7 — Sequential APIs</h4><p>Sometimes API 2 needs data from API 1.</p><pre>Login<br><br>↓<br><br>Get Token<br><br>↓<br><br>Fetch Profile<br><br>↓<br><br>Fetch Orders</pre><pre>const token = await login();<br><br>const profile = await fetchProfile(token);<br><br>const orders = await fetchOrders(profile.id);</pre><h3>Pattern 8 — Transform API Data</h3><p>Never transform inside JSX.</p><pre>{<br>users.map(user=&gt;(<br>&lt;div&gt;<br>{user.firstName+&quot; &quot;+user.lastName}<br>&lt;/div&gt;<br>))<br>}</pre><p>Instead:</p><pre>const transformedUsers = users.map(user =&gt; ({<br>    ...user,<br>    fullName: `${user.firstName} ${user.lastName}`<br>}));<br><br>// Render it <br><br>transformedUsers.map(...)<br><br>// Even better, if the transformation is expensive or reused, memoize it:<br><br>const transformedUsers = useMemo(<br>  () =&gt;<br>    users.map(user =&gt; ({<br>      ...user,<br>      fullName: `${user.firstName} ${user.lastName}`,<br>    })),<br>  [users]<br>);</pre><h4>Pattern 9 — API Caching</h4><p>Very common in senior interviews.</p><pre>Already fetched?<br><br>↓<br><br>Yes<br><br>↓<br><br>Return cached data<br><br>↓<br><br>No<br><br>↓<br><br>Call API</pre><h4>Pattern 10 — API + Search + Filter + Sort</h4><p>This is <strong>the most common machine coding question</strong>.</p><pre>API<br><br>↓<br><br>Store Original Data<br><br>↓<br><br>Search<br><br>↓<br><br>Filter<br><br>↓<br><br>Sort<br><br>↓<br><br>Pagination<br><br>↓<br><br>Render<br><br><br>// Never mutate original API data.<br><br>// Always keep - originalData - and derive the displayed data from it.</pre><h4>Senior Interview Tips</h4><p>Whenever you’re fetching data, try to think through this checklist before you start coding:</p><pre>□ Loading state?<br>□ Error state?<br>□ Empty state?<br>□ Retry?<br>□ Refresh?<br>□ AbortController?<br>□ Parallel or sequential APIs?<br>□ Data transformation?<br>□ Caching?<br>□ Memoization?<br>□ Pagination?<br>□ Search?<br>□ Filter?<br>□ Sort?</pre><h3>CHAPTER 2 — Search Patterns (Senior React)</h3><h4>What interviewers are actually testing</h4><p>When they ask:</p><blockquote><em>“Implement search.”</em></blockquote><p>They’re <strong>not</strong> checking if you know .filter().</p><p>They want to see if you can:</p><ul><li>Manage state correctly</li><li>Avoid unnecessary re-renders</li><li>Optimize expensive filtering</li><li>Handle large datasets</li><li>Avoid excessive API calls</li><li>Write reusable code</li></ul><h4>Search Pattern Roadmap</h4><p>By the end of this chapter you’ll know:</p><pre>Search<br>│<br>├── Basic Search<br>├── Case Insensitive Search<br>├── Search Multiple Fields<br>├── Search Nested Objects<br>├── Search Numbers<br>├── Debounced Search<br>├── API Search<br>├── Highlight Search<br>├── Search + Sort<br>├── Search + Filter<br>├── Search + Pagination<br>├── useMemo Optimization<br>├── Custom useDebounce Hook<br>└── Search Interview Questions</pre><h4>Pattern 1 — Basic Search</h4><h4>Interview Question</h4><blockquote><em>Display products and search by name.</em></blockquote><pre>User Types<br>      │<br>      ▼<br>Update Search State<br>      │<br>      ▼<br>Filter Data<br>      │<br>      ▼<br>Render Result<br><br>// Data<br><br>const products = [<br>  { id: 1, name: &quot;iPhone&quot; },<br>  { id: 2, name: &quot;Samsung&quot; },<br>  { id: 3, name: &quot;MacBook&quot; },<br>  { id: 4, name: &quot;Dell Laptop&quot; },<br>];<br><br>const [search, setSearch] = useState(&quot;&quot;);<br><br>&lt;input<br>   value={search}<br>   onChange={(e)=&gt;setSearch(e.target.value)}<br>/&gt;<br><br>const filteredProducts = products.filter(product =&gt;<br>    product.name.includes(search)<br>);<br><br>filteredProducts.map(product=&gt;(<br>   &lt;div key={product.id}&gt;<br>      {product.name}<br>   &lt;/div&gt;<br>))<br><br>// include() is case-sensitive so Iphone won&#39;t match iphone<br><br>const filteredProducts = products.filter(product =&gt;<br>    product.name<br>        .toLowerCase()<br>        .includes(search.toLowerCase())<br>);<br><br>// Trim Spaces<br><br>Suppose user types<br><br>&quot;    iphone      &quot;<br><br>const keyword = search.trim().toLowerCase();<br><br>const filteredProducts = products.filter(product =&gt;<br>    product.name<br>        .toLowerCase()<br>        .includes(keyword)<br>);</pre><h4>Search Multiple Fields</h4><p>Interview — Search by</p><ul><li>Name</li><li>Brand</li><li>Category</li></ul><p>Data</p><pre>const products = [<br><br>{<br>id:1,<br>name:&quot;iPhone&quot;,<br>brand:&quot;Apple&quot;,<br>category:&quot;Mobile&quot;<br>},<br><br>{<br>id:2,<br>name:&quot;Galaxy&quot;,<br>brand:&quot;Samsung&quot;,<br>category:&quot;Mobile&quot;<br>}<br><br>];<br><br>const keyword = search.toLowerCase();<br><br>const filteredProducts = products.filter(product =&gt;<br><br>product.name.toLowerCase().includes(keyword) ||<br><br>product.brand.toLowerCase().includes(keyword) ||<br><br>product.category.toLowerCase().includes(keyword)<br><br>);</pre><h4>Search Nested Objects</h4><p>Interview</p><pre>const users=[<br><br>{<br><br>id:1,<br><br>name:&quot;Rahul&quot;,<br><br>company:{<br>name:&quot;Microsoft&quot;<br>}<br><br>}<br><br>];<br><br>const filtered = users.filter(user=&gt;<br><br>user.company.name<br>.toLowerCase()<br>.includes(search.toLowerCase())<br><br>);</pre><h4>Search Numbers</h4><p>Interview</p><p>Search Product ID</p><pre>product.id<br><br>// Number doesn&#39;t have include()<br><br>// Convert<br><br>product.id<br>.toString()<br>.includes(search)</pre><h4>Search with useMemo (Senior Pattern)</h4><p>Suppose</p><pre>10,000 products<br><br>const filteredProducts = useMemo(() =&gt; {<br><br>    const keyword = search.trim().toLowerCase();<br><br>    return products.filter(product =&gt;<br><br>        product.name<br>            .toLowerCase()<br>            .includes(keyword)<br><br>    );<br><br>}, [products, search]);<br><br><br>Render<br><br>↓<br><br>Search unchanged<br><br>↓<br><br>useMemo returns cached value<br><br>↓<br><br>No filtering</pre><p>Interview question</p><p><strong>When should you use useMemo?</strong></p><p>Answer</p><p>When</p><ul><li>expensive calculation</li><li>huge list</li><li>unnecessary recalculation</li></ul><p>NOT for — 5 items</p><h4>Empty Search</h4><p>If search is empty</p><p>Don’t filter.</p><pre>const keyword = search.trim().toLowerCase();<br><br>const filteredProducts = products.filter(product =&gt; {<br><br>if(!keyword)<br>return true;<br><br>return product.name<br>.toLowerCase()<br>.includes(keyword);<br><br>});<br><br><br><br><br>// Highlight Search Text<br><br>const parts = product.name.split(<br>    new RegExp(`(${search})`, &quot;gi&quot;)<br>);<br><br>// Render<br><br>parts.map(part =&gt;<br><br>part.toLowerCase()===search.toLowerCase()<br><br>?<br><br>&lt;b&gt;{part}&lt;/b&gt;<br><br>:<br><br>part<br><br>)</pre><h4>Search Large Dataset</h4><p>Interview</p><pre>100,000 products</pre><p>Use</p><ul><li>useMemo</li><li>Virtualization</li><li>Debounce</li><li>Pagination</li></ul><p>Not</p><pre>filter()<br><br>↓<br><br>render 100000 divs<br><br><br>// Generate <br><br>const products = Array.from({ length: 100000 }, (_, index) =&gt; ({<br>  id: index + 1,<br>  name: `Product ${index + 1}`,<br>  price: Math.floor(Math.random() * 5000),<br>}));<br><br>// Debounce<br><br>import { useState, useEffect } from &quot;react&quot;;<br><br>function useDebounce(value, delay = 500) {<br>  const [debouncedValue, setDebouncedValue] = useState(value);<br><br>  useEffect(() =&gt; {<br>    const timer = setTimeout(() =&gt; {<br>      setDebouncedValue(value);<br>    }, delay);<br><br>    return () =&gt; clearTimeout(timer);<br>  }, [value, delay]);<br><br>  return debouncedValue;<br>}<br><br>// Search + useMemo<br><br>const [search, setSearch] = useState(&quot;&quot;);<br><br>const debouncedSearch = useDebounce(search, 300);<br><br>const filteredProducts = useMemo(() =&gt; {<br>  return products.filter(product =&gt;<br>    product.name<br>      .toLowerCase()<br>      .includes(debouncedSearch.toLowerCase())<br>  );<br>}, [debouncedSearch]);<br><br>//Pagination<br><br>const ITEMS_PER_PAGE = 20;<br><br>const [page, setPage] = useState(1);<br><br>const paginatedProducts = useMemo(() =&gt; {<br>  const start = (page - 1) * ITEMS_PER_PAGE;<br><br>  return filteredProducts.slice(<br>    start,<br>    start + ITEMS_PER_PAGE<br>  );<br>}, [page, filteredProducts]);<br><br><br>// Total Pages<br><br>const totalPages = Math.ceil(<br>  filteredProducts.length / ITEMS_PER_PAGE<br>);<br><br>// Buttons<br><br>&lt;button<br>onClick={() =&gt; setPage(p =&gt; p - 1)}<br>disabled={page === 1}<br>&gt;<br>Previous<br>&lt;/button&gt;<br><br>&lt;span&gt;{page}&lt;/span&gt;<br><br>&lt;button<br>onClick={() =&gt; setPage(p =&gt; p + 1)}<br>disabled={page === totalPages}<br>&gt;<br>Next<br>&lt;/button&gt;<br></pre><h4>Interview Follow-up</h4><p><strong>Q. Why not store filtered data in state?</strong></p><p>Answer</p><p>Because</p><pre>Filtered Data<br><br>=<br><br>Derived State</pre><p>Derived data should usually be computed from the source data instead of stored separately, otherwise you risk having two sources of truth.</p><h4>CHAPTER 3 — Filtering Patterns (Senior React)</h4><h4>What interviewers are testing</h4><p>When they say:</p><blockquote><em>Build filters for a Product Listing Page.</em></blockquote><p>They are testing:</p><ul><li>Array methods (filter)</li><li>State management</li><li>Derived state</li><li>useMemo</li><li>Combining multiple conditions</li><li>UI state synchronization</li><li>Clean architecture</li></ul><h4>The Golden Rule</h4><p><strong>Never mutate your original data.</strong></p><p>Always keep:</p><pre>const [products, setProducts] = useState(apiData);<br><br>// Never do this<br><br>setProducts(products.filter(...));<br><br>// Why?<br><br>Original Data ❌ Lost<br><br>// Instead<br><br>Original Data<br><br>↓<br><br>Search<br><br>↓<br><br>Filter<br><br>↓<br><br>Sort<br><br>↓<br><br>Pagination<br><br>↓<br><br>Render</pre><p>Every step should produce <strong>derived data</strong>, not overwrite the source.</p><p>Sample data:</p><pre>const products = [<br>  {<br>    id: 1,<br>    name: &quot;iPhone 16&quot;,<br>    brand: &quot;Apple&quot;,<br>    category: &quot;Mobile&quot;,<br>    price: 1200,<br>    rating: 4.8,<br>    inStock: true,<br>  },<br>  {<br>    id: 2,<br>    name: &quot;Galaxy S25&quot;,<br>    brand: &quot;Samsung&quot;,<br>    category: &quot;Mobile&quot;,<br>    price: 1000,<br>    rating: 4.5,<br>    inStock: false,<br>  },<br>  {<br>    id: 3,<br>    name: &quot;MacBook Pro&quot;,<br>    brand: &quot;Apple&quot;,<br>    category: &quot;Laptop&quot;,<br>    price: 2200,<br>    rating: 4.9,<br>    inStock: true,<br>  },<br>  {<br>    id: 4,<br>    name: &quot;Dell XPS&quot;,<br>    brand: &quot;Dell&quot;,<br>    category: &quot;Laptop&quot;,<br>    price: 1800,<br>    rating: 4.7,<br>    inStock: true,<br>  },<br>];</pre><h4>Pattern 1 — Single Filter</h4><p>Interview</p><blockquote><em>Show only Apple products.</em></blockquote><p>Logic:</p><pre>Products<br><br>↓<br><br>Brand === Apple<br><br>↓<br><br>Display<br><br><br>const filteredProducts = products.filter(<br>  product =&gt; product.brand === &quot;Apple&quot;<br>);<br><br>o(n) // Complexity</pre><h4>Pattern 2 — Dropdown Filter</h4><p>Interview</p><pre>All<br><br>Apple<br><br>Samsung<br><br>Dell<br><br>const [brand, setBrand] = useState(&quot;All&quot;);<br><br>&lt;select<br>  value={brand}<br>  onChange={(e) =&gt; setBrand(e.target.value)}<br>&gt;<br>  &lt;option&gt;All&lt;/option&gt;<br>  &lt;option&gt;Apple&lt;/option&gt;<br>  &lt;option&gt;Samsung&lt;/option&gt;<br>  &lt;option&gt;Dell&lt;/option&gt;<br>&lt;/select&gt;<br><br><br>const filteredProducts = products.filter(product =&gt; {<br><br>  if (brand === &quot;All&quot;) return true;<br><br>  return product.brand === brand;<br><br>});<br><br><br>Dropdown<br><br>↓<br><br>Brand Selected<br><br>↓<br><br>Filter<br><br>↓<br><br>Render</pre><h4>Pattern 3 — Checkbox Filter (Multiple Selection)</h4><p>Interview</p><p>User selects</p><pre>☑ Apple<br><br>☑ Samsung<br><br>const [selectedBrands, setSelectedBrands] = useState([]);<br><br>// Toggle logic<br><br>const handleBrand = (brand) =&gt; {<br><br>  setSelectedBrands(prev =&gt;<br><br>    prev.includes(brand)<br><br>      ? prev.filter(item =&gt; item !== brand)<br><br>      : [...prev, brand]<br><br>  );<br><br>};<br><br><br>Checkbox<br><br>↓<br><br>Already Selected?<br><br>↓<br><br>Yes → Remove<br><br>No → Add<br><br>↓<br><br>Update Array<br><br>// Filtering<br><br>const filteredProducts = products.filter(product =&gt; {<br><br>  if (selectedBrands.length === 0) return true;<br><br>  return selectedBrands.includes(product.brand);<br><br>});</pre><h4>Pattern 4 — Price Range Filter</h4><p>Interview</p><pre>Min = 500<br><br>Max = 1500<br><br>const [minPrice, setMinPrice] = useState(0);<br>const [maxPrice, setMaxPrice] = useState(5000);<br><br>const filteredProducts = products.filter(product =&gt;<br><br>  product.price &gt;= minPrice &amp;&amp;<br>  product.price &lt;= maxPrice<br><br>);<br><br>Price<br><br>↓<br><br>Within Range?<br><br>↓<br><br>Yes<br><br>↓<br><br>Display</pre><h4>Pattern 5 — Rating Filter</h4><p>Interview</p><pre>★★★★☆ &amp; Above<br><br>const [rating, setRating] = useState(0);<br><br>const filteredProducts = products.filter(product =&gt;<br><br>  product.rating &gt;= rating<br><br>);</pre><h4>Pattern 6 — Boolean Filter</h4><p>Interview</p><pre>☑ In Stock<br><br>const [inStockOnly, setInStockOnly] = useState(false);<br><br>const filteredProducts = products.filter(product =&gt; {<br><br>  if (!inStockOnly) return true;<br><br>  return product.inStock;<br><br>});<br><br></pre><h4>Pattern 7 — Multiple Filters</h4><p>This is the most common interview question.</p><p>Requirements</p><ul><li>Brand</li><li>Category</li><li>Price</li><li>Rating</li><li>Stock</li></ul><p>Flow</p><pre>Products<br><br>↓<br><br>Brand<br><br>↓<br><br>Category<br><br>↓<br><br>Price<br><br>↓<br><br>Rating<br><br>↓<br><br>Stock<br><br>↓<br><br>Render<br><br><br>const filteredProducts = useMemo(() =&gt; {<br><br>  return products.filter(product =&gt; {<br><br>    const brandMatch =<br>      brand === &quot;All&quot; || product.brand === brand;<br><br>    const categoryMatch =<br>      category === &quot;All&quot; || product.category === category;<br><br>    const priceMatch =<br>      product.price &gt;= minPrice &amp;&amp;<br>      product.price &lt;= maxPrice;<br><br>    const ratingMatch =<br>      product.rating &gt;= rating;<br><br>    const stockMatch =<br>      !inStockOnly || product.inStock;<br><br>    return (<br>      brandMatch &amp;&amp;<br>      categoryMatch &amp;&amp;<br>      priceMatch &amp;&amp;<br>      ratingMatch &amp;&amp;<br>      stockMatch<br>    );<br><br>  });<br><br>}, [<br>  products,<br>  brand,<br>  category,<br>  minPrice,<br>  maxPrice,<br>  rating,<br>  inStockOnly<br>]);</pre><p>You create readable variables.</p><p>This is exactly how senior engineers write filtering logic.</p><h4>Pattern 8 — Search + Filter</h4><p>Most interviews combine these.</p><p>Pipeline</p><pre>Products<br><br>↓<br><br>Search<br><br>↓<br><br>Brand Filter<br><br>↓<br><br>Category Filter<br><br>↓<br><br>Price Filter<br><br>↓<br><br>Render<br><br><br>// Code<br><br>const filteredProducts = useMemo(() =&gt; {<br><br>  const keyword = search.trim().toLowerCase();<br><br>  return products.filter(product =&gt; {<br><br>    const searchMatch =<br>      !keyword ||<br>      product.name.toLowerCase().includes(keyword);<br><br>    const brandMatch =<br>      brand === &quot;All&quot; ||<br>      product.brand === brand;<br><br>    return searchMatch &amp;&amp; brandMatch;<br><br>  });<br><br>}, [products, search, brand]);</pre><h4>Pattern 9 — Dynamic Filters</h4><p>Interview</p><p>Categories come from API.</p><p>Don’t hardcode.</p><p>Generate dynamically.</p><pre>const categories = [<br>  &quot;All&quot;,<br>  ...new Set(products.map(product =&gt; product.category))<br>];<br><br>// Result<br><br>All<br><br>Mobile<br><br>Laptop<br><br>// Same idea works for brands.</pre><h4>Pattern 10 — Reset Filters</h4><p>Interview</p><pre>// Reset button<br><br>const resetFilters = () =&gt; {<br><br>  setBrand(&quot;All&quot;);<br><br>  setCategory(&quot;All&quot;);<br><br>  setMinPrice(0);<br><br>  setMaxPrice(5000);<br><br>  setRating(0);<br><br>  setInStockOnly(false);<br><br>};</pre><h4>Pattern 11 — Search + Filter + Sort</h4><p>Pipeline matters.</p><pre>Products<br><br>↓<br><br>Search<br><br>↓<br><br>Filter<br><br>↓<br><br>Sort<br><br>↓<br><br>Render<br><br><br><br><br>// Search + Filter + Pagination<br><br>Products<br><br>↓<br><br>Search<br><br>↓<br><br>Filter<br><br>↓<br><br>Sort<br><br>↓<br><br>Pagination<br><br>↓<br><br>Render</pre><p>Avoid sorting before filtering, because you would sort items that might be discarded.</p><p>Pagination should always happen <strong>last</strong>.</p><h4>Server-side Filtering</h4><p>Interview</p><p>Dataset</p><pre>10 million products<br><br>// Don&#39;t do <br><br>products.filter(...)<br><br>// Instead<br><br>API<br><br>↓<br><br>brand=Apple<br><br>↓<br><br>price=1000<br><br>↓<br><br>category=Mobile<br><br>// example<br><br>fetch(<br>  `/products?brand=${brand}&amp;category=${category}`<br>);</pre><h4>Generic Filter Function (Senior Pattern)</h4><p>Suppose multiple pages need filtering.</p><p>Instead of duplicating logic:</p><pre>const applyFilters = ({<br>  products,<br>  brand,<br>  category,<br>  minPrice,<br>  maxPrice,<br>  rating,<br>  inStockOnly,<br>}) =&gt; {<br>  return products.filter(product =&gt; {<br>    const brandMatch =<br>      brand === &quot;All&quot; || product.brand === brand;<br><br>    const categoryMatch =<br>      category === &quot;All&quot; || product.category === category;<br><br>    const priceMatch =<br>      product.price &gt;= minPrice &amp;&amp;<br>      product.price &lt;= maxPrice;<br><br>    const ratingMatch =<br>      product.rating &gt;= rating;<br><br>    const stockMatch =<br>      !inStockOnly || product.inStock;<br><br>    return (<br>      brandMatch &amp;&amp;<br>      categoryMatch &amp;&amp;<br>      priceMatch &amp;&amp;<br>      ratingMatch &amp;&amp;<br>      stockMatch<br>    );<br>  });<br>};</pre><h4>Senior Product Listing Template</h4><p>This is the template I would use in an interview.</p><pre>const visibleProducts = useMemo(() =&gt; {<br>  const keyword = search.trim().toLowerCase();<br><br>  return products<br>    .filter((product) =&gt; {<br>      const searchMatch =<br>        !keyword ||<br>        product.name.toLowerCase().includes(keyword);<br><br>      const brandMatch =<br>        brand === &quot;All&quot; || product.brand === brand;<br><br>      const categoryMatch =<br>        category === &quot;All&quot; ||<br>        product.category === category;<br><br>      const priceMatch =<br>        product.price &gt;= minPrice &amp;&amp;<br>        product.price &lt;= maxPrice;<br><br>      return (<br>        searchMatch &amp;&amp;<br>        brandMatch &amp;&amp;<br>        categoryMatch &amp;&amp;<br>        priceMatch<br>      );<br>    })<br>    .sort(sortProducts)<br>    .slice(startIndex, endIndex);<br>}, [<br>  products,<br>  search,<br>  brand,<br>  category,<br>  minPrice,<br>  maxPrice,<br>  sortProducts,<br>  startIndex,<br>  endIndex,<br>]);<br><br><br>Source Data<br>    ↓<br>Search<br>    ↓<br>Filter<br>    ↓<br>Sort<br>    ↓<br>Paginate<br>    ↓<br>Render</pre><h4>CHAPTER 4 — Sorting Patterns (Senior React)</h4><h4>What Interviewers are Testing</h4><p>When they ask</p><blockquote><em>Sort products by Price</em></blockquote><p>They are actually testing</p><ul><li>Array.sort()</li><li>Comparator function</li><li>Immutability</li><li>Derived state</li><li>React rendering</li><li>Performance</li></ul><pre>const products = [<br>  {<br>    id: 1,<br>    name: &quot;iPhone&quot;,<br>    price: 1200,<br>    rating: 4.8,<br>    createdAt: &quot;2025-01-15&quot;<br>  },<br>  {<br>    id: 2,<br>    name: &quot;Samsung&quot;,<br>    price: 1000,<br>    rating: 4.5,<br>    createdAt: &quot;2025-03-01&quot;<br>  },<br>  {<br>    id: 3,<br>    name: &quot;MacBook&quot;,<br>    price: 2200,<br>    rating: 4.9,<br>    createdAt: &quot;2025-02-20&quot;<br>  }<br>];</pre><h4>Understanding sort()</h4><p>Many people think</p><pre>sort()<br><br>creates a new array.<br><br>❌ Wrong.<br><br>It modifies the original array.<br><br>Example<br><br>const arr = [4,2,1];<br><br>arr.sort();<br><br>console.log(arr);<br><br>// output - [1,2,4]</pre><h4>Golden Rule</h4><p>Never</p><pre>products.sort(...)</pre><p>Instead</p><pre>[...products].sort(...)</pre><p>Always copy first.</p><p>why?</p><pre>Original Array<br><br>↓<br><br>Copy<br><br>↓<br><br>Sort Copy<br><br>↓<br><br>Render</pre><p>Original state remains unchanged.</p><h4>Pattern 1 — Ascending Numbers</h4><p>Interview</p><p>Sort price low → high</p><p>Because default sorting is <strong>string sorting</strong>.</p><pre>const sorted = [...products].sort(<br>    (a,b)=&gt;a.price-b.price<br>);<br><br><br>a.price - b.price<br><br>Negative<br><br>↓<br><br>a comes first<br><br>200-500<br><br>=<br><br>-300<br><br>↓<br><br>200 before 500</pre><h4>Pattern 2 — Descending Numbers</h4><p>High → Low</p><pre>const sorted = [...products].sort(<br>    (a,b)=&gt;b.price-a.price<br>);<br><br>Price<br><br>↓<br><br>Largest<br><br>↓<br><br>Smallest<br></pre><h4>Pattern 3 — Alphabetical Sorting</h4><p>Interview</p><p>Sort names</p><pre>const sorted = [...products].sort(<br>   (a,b)=&gt;a.name.localeCompare(b.name)<br>);<br><br>// Descending<br><br>const sorted = [...products].sort(<br>   (a,b)=&gt;b.name.localeCompare(a.name)<br>);</pre><p>Because</p><p>localeCompare() — Always prefer for strings.</p><p>handles</p><ul><li>uppercase</li><li>lowercase</li><li>accents</li><li>international languages</li></ul><h4>Pattern 4 — Date Sorting</h4><p>Interview</p><p>Newest First</p><pre>const sorted=[...products].sort(<br><br>(a,b)=&gt;<br><br>new Date(b.createdAt)-new Date(a.createdAt)<br><br>);</pre><p>Oldest</p><pre>const sorted=[...products].sort(<br><br>(a,b)=&gt;<br><br>new Date(a.createdAt)-new Date(b.createdAt)<br><br>);</pre><h4>Pattern 5 — Rating Sorting</h4><p>Highest Rating</p><pre>const sorted=[...products].sort(<br><br>(a,b)=&gt;b.rating-a.rating<br><br>);</pre><h4>Pattern 6 — Multiple Sorting</h4><p>Interview</p><p>Sort by</p><p>Rating</p><p>↓</p><p>Price</p><p>Logic</p><pre>Same Rating?<br><br>↓<br><br>Yes<br><br>↓<br><br>Compare Price<br><br>↓<br><br>No<br><br>↓<br><br>Compare Rating<br><br><br>const sorted = [...products].sort((a,b)=&gt;{<br><br>if(a.rating!==b.rating){<br><br>return b.rating-a.rating;<br><br>}<br><br>return a.price-b.price;<br><br>});<br><br><br>Rating<br><br>↓<br><br>4.8<br><br>↓<br><br>Price<br><br>↓<br><br>1000<br><br>↓<br><br>1200</pre><h4>Pattern 7 — Dynamic Sorting</h4><p>Most common interview question.</p><p>Dropdown</p><pre>Price Low<br><br>Price High<br><br>Name<br><br>Rating<br><br>Newest<br><br><br>const [sortBy,setSortBy]=useState(&quot;&quot;);<br><br><br>&lt;select<br>value={sortBy}<br>onChange={(e)=&gt;setSortBy(e.target.value)}<br>&gt;<br><br>&lt;option value=&quot;&quot;&gt;<br>Default<br>&lt;/option&gt;<br><br>&lt;option value=&quot;priceLow&quot;&gt;<br>Price Low<br>&lt;/option&gt;<br><br>&lt;option value=&quot;priceHigh&quot;&gt;<br>Price High<br>&lt;/option&gt;<br><br>&lt;option value=&quot;name&quot;&gt;<br>Name<br>&lt;/option&gt;<br><br>&lt;option value=&quot;rating&quot;&gt;<br>Rating<br>&lt;/option&gt;<br><br>&lt;/select&gt;<br><br><br>const sortedProducts = [...products];<br><br>switch(sortBy){<br><br>case &quot;priceLow&quot;:<br><br>sortedProducts.sort((a,b)=&gt;a.price-b.price);<br><br>break;<br><br>case &quot;priceHigh&quot;:<br><br>sortedProducts.sort((a,b)=&gt;b.price-a.price);<br><br>break;<br><br>case &quot;name&quot;:<br><br>sortedProducts.sort((a,b)=&gt;<br><br>a.name.localeCompare(b.name)<br><br>);<br><br>break;<br><br>case &quot;rating&quot;:<br><br>sortedProducts.sort((a,b)=&gt;<br><br>b.rating-a.rating<br><br>);<br><br>break;<br><br>default:<br><br>break;<br><br>}</pre><h4>Reusable sortFunction</h4><p>Senior Pattern</p><pre>const sortProducts = (products, sortBy) =&gt; {<br>  const sorted = [...products];<br><br>  switch (sortBy) {<br>    case &quot;priceLow&quot;:<br>      sorted.sort((a, b) =&gt; a.price - b.price);<br>      break;<br><br>    case &quot;priceHigh&quot;:<br>      sorted.sort((a, b) =&gt; b.price - a.price);<br>      break;<br><br>    case &quot;rating&quot;:<br>      sorted.sort((a, b) =&gt; b.rating - a.rating);<br>      break;<br><br>    case &quot;name&quot;:<br>      sorted.sort((a, b) =&gt;<br>        a.name.localeCompare(b.name)<br>      );<br>      break;<br><br>    case &quot;newest&quot;:<br>      sorted.sort(<br>        (a, b) =&gt;<br>          new Date(b.createdAt) -<br>          new Date(a.createdAt)<br>      );<br>      break;<br><br>    default:<br>      break;<br>  }<br><br>  return sorted;<br>};<br><br><br><br><br>// Usage<br><br>const visibleProducts = useMemo(() =&gt; {<br>  return sortProducts(filteredProducts, sortBy);<br>}, [filteredProducts, sortBy]);<br></pre><h3>Sorting API Data</h3><p>Never</p><pre>setProducts(<br>products.sort(...)<br>);</pre><p>Instead</p><pre>const sortedProducts =<br>[...products].sort(...);</pre><p>Original data remains untouched.</p><h4>Interview Follow-up</h4><p><strong>Q:</strong> Why do we use [...products].sort() instead of products.sort() in React?</p><p><strong>Answer:</strong></p><ul><li>sort() mutates the original array.</li><li>React state should be treated as immutable.</li><li>Mutating state directly can lead to bugs, missed re-renders, and unpredictable UI updates.</li><li>By copying first ([...products]), we keep the original state unchanged and return a newly sorted array.</li></ul><h4>Complexity</h4><pre>const sortedProducts = [...products].sort(compareFn);</pre><ul><li>Spread ([...]): <strong>O(n)</strong> time, <strong>O(n)</strong> space</li><li>sort(): <strong>O(n log n)</strong> time (typically), <strong>O(log n)</strong> auxiliary space depending on the engine</li></ul><p>Overall:</p><ul><li><strong>Time:</strong> O(n log n)</li><li><strong>Space:</strong> O(n) (because of the copied array)</li></ul><h4>CHAPTER 5 — Pagination Patterns (Senior React)</h4><h4>What Interviewers are Testing</h4><p>When they ask</p><blockquote><em>“Implement pagination”</em></blockquote><p>They are testing</p><ul><li>Array slicing</li><li>State management</li><li>Math</li><li>Performance</li><li>API understanding</li><li>Edge cases</li></ul><pre>API<br><br>↓<br><br>Search<br><br>↓<br><br>Filter<br><br>↓<br><br>Sort<br><br>↓<br><br>Pagination<br><br>↓<br><br>Render</pre><p>Pagination is ALWAYS the last transformation.</p><p>Types of Pagination</p><pre>Pagination<br><br>│<br><br>├── Client-side<br><br>├── Server-side<br><br>├── Infinite Scroll<br><br>├── Cursor Pagination<br><br>└── Virtualization</pre><h4>Pattern 1 — Client-side Pagination</h4><p>Most common interview question.</p><p>Suppose</p><pre>100 Products<br><br>// show <br>10 per page<br><br>// state<br><br>const [currentPage, setCurrentPage] = useState(1);<br><br>const itemsPerPage = 10;<br><br>// Calculate Indices<br><br>const startIndex = (currentPage - 1) * itemsPerPage;<br><br>const endIndex = startIndex + itemsPerPage;<br><br>// Page 1<br><br>start<br><br>(1-1)*10<br><br>= 0<br><br>end<br><br>0+10<br><br>= 10<br><br>// show - 0 → 9<br><br>// Page 2<br><br>start<br><br>(2-1)*10<br><br>= 10<br><br>end = 20<br><br>// show 10 → 19<br><br><br>// Step 3 - Slice<br><br>const visibleProducts = products.slice(<br>    startIndex,<br>    endIndex<br>);<br><br>100 Products<br><br>↓<br><br>slice(20,30)<br><br>↓<br><br>10 Products<br><br>↓<br><br>Render<br></pre><pre>const [currentPage, setCurrentPage] = useState(1);<br><br>const itemsPerPage = 10;<br><br>const startIndex =<br>(currentPage-1)*itemsPerPage;<br><br>const endIndex =<br>startIndex+itemsPerPage;<br><br>const visibleProducts =<br>products.slice(startIndex,endIndex);</pre><h4>Pattern 2 — Total Pages</h4><p>Interview</p><p>How many buttons?</p><p>Need</p><pre>const totalPages = Math.ceil(<br>    products.length / itemsPerPage<br>);<br><br>Example<br><br>95 Products<br><br>95/10<br><br>=<br><br>9.5<br><br>↓<br><br>10 Pages // need Math.ceil() but never Math.floor()</pre><h4>Generate Buttons</h4><pre>{<br>Array.from(<br>{<br>length:totalPages<br>},<br>(_,index)=&gt;(<br><br>&lt;button<br><br>key={index}<br><br>onClick={()=&gt;setCurrentPage(index+1)}<br><br>&gt;<br><br>{index+1}<br><br>&lt;/button&gt;<br><br>))<br>}<br><br>// output<br><br>1<br><br>2<br><br>3<br><br>4<br><br>5</pre><h4>Previous Button</h4><pre>&lt;button<br><br>disabled={currentPage===1}<br><br>onClick={()=&gt;setCurrentPage(prev=&gt;prev-1)}<br><br>&gt;<br><br>Previous<br><br>&lt;/button&gt;</pre><h4>Next button</h4><pre>&lt;button<br><br>disabled={currentPage===totalPages}<br><br>onClick={()=&gt;setCurrentPage(prev=&gt;prev+1)}<br><br>&gt;<br><br>Next<br><br>&lt;/button&gt;<br><br>Next<br><br>↓<br><br>currentPage++<br><br>↓<br><br>Recalculate slice<br><br>↓<br><br>Render</pre><h4>First Page &amp; Last Page</h4><pre>// First page<br><br>&lt;button<br><br>onClick={()=&gt;setCurrentPage(1)}<br><br>&gt;<br><br>First<br><br>&lt;/button&gt;<br><br>// last page<br><br>&lt;button<br><br>onClick={()=&gt;setCurrentPage(totalPages)}<br><br>&gt;<br><br>Last<br><br>&lt;/button&gt;</pre><h4>Search + Pagination</h4><p>Suppose</p><pre>Page 6</pre><p>Search</p><pre>MacBook</pre><p>Only</p><pre>1 Result</pre><p>Page 6</p><p>↓</p><p>Empty</p><p>Wrong.</p><p>Correct</p><p>Whenever</p><p>Search changes</p><p>↓</p><p>Go to</p><p>Page 1</p><pre>useEffect(()=&gt;{<br><br>setCurrentPage(1);<br><br>},[search]);</pre><p>Also do this for</p><ul><li>filters</li><li>sorting</li></ul><h4>Generic usePagination Hook</h4><pre>function usePagination(data,pageSize){<br><br>const [currentPage,setCurrentPage]=useState(1);<br><br>const totalPages=Math.ceil(<br><br>data.length/pageSize<br><br>);<br><br>const currentItems=useMemo(()=&gt;{<br><br>const start=<br><br>(currentPage-1)*pageSize;<br><br>return data.slice(<br><br>start,<br><br>start+pageSize<br><br>);<br><br>},[<br>data,<br>currentPage,<br>pageSize<br>]);<br><br>return{<br><br>currentPage,<br><br>setCurrentPage,<br><br>totalPages,<br><br>currentItems<br><br>};<br><br>}</pre><p>Usage:</p><pre>const{<br><br>currentItems,<br><br>currentPage,<br><br>setCurrentPage,<br><br>totalPages<br><br>}<br><br>=<br><br>usePagination(products,10);</pre><h4>React Memoization (useMemo, useCallback, React.memo)</h4><p>Most candidates memorize:</p><ul><li>useMemo → memoize value</li><li>useCallback → memoize function</li><li>React.memo → memoize component</li></ul><p>That answer is <strong>not enough</strong> for a senior interview.</p><p>A senior engineer first understands <strong>why React re-renders</strong>, then decides whether memoization is needed.</p><h4>What Interviewers Are Actually Testing</h4><p>When they ask</p><blockquote><em>Explain useMemo.</em></blockquote><p>They’re actually testing</p><ul><li>React Rendering</li><li>Reference Equality</li><li>Performance</li><li>Re-rendering</li><li>JavaScript Objects</li><li>Functions</li><li>Closures</li></ul><h4>PART 1</h4><h4>How React Actually Renders</h4><p>Suppose</p><pre>function App(){<br><br>console.log(&quot;App Render&quot;);<br><br>return &lt;Child/&gt;<br><br>}<br><br>// React Runs - Whenever state changes<br><br>App()<br><br>↓<br><br>Child()<br><br>↓<br><br>GrandChild()<br><br>↓<br><br>...<br><br><br>// React does NOT update only one line.<br><br>It calls the component again.<br><br>Why?<br><br>Because<br><br>Parent rendered.<br><br>Children render too.<br><br><br>// Can We Stop This?<br><br>Yes.<br><br>React.memo()</pre><h4>PART 2</h4><h4>React.memo</h4><p>Interview</p><p>Parent</p><p>Updates</p><p>↓</p><p>Child</p><p>Has Same Props</p><p>↓</p><p>Don’t Render</p><pre>// Without React.memo<br><br>Parent<br><br>↓<br><br>Child<br><br>↓<br><br>Child<br><br>↓<br><br>Child<br><br>↓<br><br>Child<br><br>// With React.memo<br><br>Parent<br><br>↓<br><br>Same Props?<br><br>↓<br><br>Yes<br><br>↓<br><br>Skip Render<br><br><br>// Important<br><br>React.memo<br><br>Compares<br><br>Props<br><br>Not State.</pre><h4>PART 3</h4><h4>Why React.memo Sometimes Doesn’t Work</h4><p>Interview favorite.</p><p>Parent</p><pre>&lt;Child<br><br>user={{<br><br>name:&quot;Rahul&quot;<br><br>}}<br><br>/&gt;<br><br>Looks Same.<br><br>But Every render Creates<br><br>New Object.<br><br>Memory<br><br>------------------------------<br><br>Render 1<br><br>Object A<br><br>↓<br><br>Render 2<br><br>Object B<br><br><br>React<br><br>Sees A !== B<br><br>So Child Renders Again.</pre><p>Solution — <strong>useMemo</strong></p><h4>PART 4</h4><h4>useMemo</h4><p>Definition</p><p>Memoize</p><p>A</p><p>Value.</p><pre>const obj={<br><br>name:&quot;Rahul&quot;<br><br>};<br><br>Every render<br><br>↓<br><br>New Object<br><br>↓<br><br>New Reference</pre><p>Instead</p><pre>const user = useMemo(()=&gt;{<br><br>return{<br><br>name:&quot;Rahul&quot;<br><br>}<br><br>},[]);<br><br>// Now Same Reference.<br><br>Render<br><br>↓<br><br>Dependencies Changed?<br><br>↓<br><br>No<br><br>↓<br><br>Return Cached Value<br><br><br>const expensiveValue = useMemo(() =&gt; {<br><br>return heavyCalculation();<br><br>}, []);<br><br>heavyCalculation()<br><br>Runs<br><br>Only Once.<br><br><br>// Machine coding<br><br>const visibleProducts=useMemo(()=&gt;{<br><br>...<br><br>},[<br>products,<br>search,<br>filter,<br>sort<br>]);</pre><h4>PART 5</h4><h4>useCallback</h4><p>Definition</p><p>Memoize</p><p>A</p><p>Function.</p><pre>const handleClick=()=&gt;{<br><br>console.log(&quot;Click&quot;);<br><br>}<br><br>Every Render<br><br>↓<br><br>New Function.<br>-------------------------------<br><br>Function A<br><br>↓<br><br>Function B<br><br>↓<br><br>Function C<br>-------------------------------<br><br>Child<br><br>Receives<br><br>Different Function<br><br>↓<br><br>Render Again.<br>------------------------------<br>// Solution <br><br>const handleClick = useCallback(()=&gt;{<br><br>console.log(&quot;Click&quot;);<br><br>},[]);<br><br>Now Function Reference Same.</pre><h4>When NOT to Use Memoization</h4><p>This is the answer that impresses interviewers.</p><p>Don’t use it for:</p><ul><li>Tiny calculations (count + 1)</li><li>Components that render quickly</li><li>Small lists</li><li>Values that are inexpensive to compute</li><li>Functions that aren’t passed to memoized children</li></ul><p>Why?</p><p>Memoization itself has a cost:</p><ul><li>React must store the cached value/function.</li><li>React must compare dependencies on every render.</li><li>More code to maintain.</li></ul><p>Use memoization only when it solves a measurable problem.</p><h4>Real Machine Coding Example</h4><p>Product Listing</p><pre>const searched = useMemo(() =&gt; {<br>  return searchProducts(products, search);<br>}, [products, search]);<br><br>const filtered = useMemo(() =&gt; {<br>  return filterProducts(searched, filters);<br>}, [searched, filters]);<br><br>const sorted = useMemo(() =&gt; {<br>  return sortProducts(filtered, sortBy);<br>}, [filtered, sortBy]);<br><br>const paginated = useMemo(() =&gt; {<br>  return paginate(sorted, page, pageSize);<br>}, [sorted, page, pageSize]);<br><br>const handleDelete = useCallback((id) =&gt; {<br>  setProducts(prev =&gt; prev.filter(p =&gt; p.id !== id));<br>}, []);<br><br>return (<br>  &lt;ProductTable<br>    products={paginated}<br>    onDelete={handleDelete}<br>  /&gt;<br>);<br><br><br><br>// Then optimize the child:<br><br>const ProductTable = React.memo(function ProductTable({<br>  products,<br>  onDelete,<br>}) {<br>  return (<br>    &lt;&gt;<br>      {products.map(product =&gt; (<br>        &lt;ProductRow<br>          key={product.id}<br>          product={product}<br>          onDelete={onDelete}<br>        /&gt;<br>      ))}<br>    &lt;/&gt;<br>  );<br>});<br><br><br>// Questions<br><br>Q1. Why does React.memo not work sometimes?<br><br>Answer:<br>Because one or more props receive a new reference every render <br>(new object, array, or function). React.memo performs a shallow comparison, <br>so different references trigger a re-render.<br></pre><h3>Custom Hooks (Senior React)</h3><h4>What Interviewers Are Testing</h4><p>When they ask</p><blockquote><em>Create a custom hook.</em></blockquote><p>They are testing</p><ul><li>React Hooks</li><li>Reusability</li><li>Separation of concerns</li><li>Clean architecture</li><li>API design</li><li>Side effects</li><li>Performance</li></ul><h4>What is a Custom Hook?</h4><p>A custom hook is <strong>just a JavaScript function</strong> that:</p><ul><li>Starts with use</li><li>Can use React hooks (useState, useEffect, etc.)</li><li>Encapsulates reusable logic</li><li>Returns data and/or functions</li></ul><pre>Rule #1<br><br>// Never do this<br><br>function fetchUsers() {<br><br>const [users,setUsers]=useState([]);<br><br>}<br><br>React won&#39;t recognize it as a Hook because it doesn&#39;t start with use.<br><br>// Correct<br><br>function useFetch(){<br><br>}<br>----------------------------------------------<br>Rule #2<br><br>Only call hooks<br><br>at the top level<br>never inside loops<br>never inside if statements<br><br>Wrong<br><br>if(user){<br><br>useEffect(()=&gt;{},[]);<br><br>}<br><br>Correct<br><br>useEffect(() =&gt; {<br>  if (!user) return;<br><br>  // logic<br>}, [user]);</pre><h4>Pattern 1 — useToggle</h4><p>Interview</p><p>Modal</p><p>Dark Theme</p><p>Sidebar</p><p>Accordion</p><p>Dropdown</p><p>All need toggle logic.</p><pre>function useToggle(initial = false) {<br>  const [value, setValue] = useState(initial);<br><br>  const toggle = () =&gt; {<br>    setValue(prev =&gt; !prev);<br>  };<br><br>  return {<br>    value,<br>    toggle,<br>    setValue<br>  };<br>}<br><br>// Usage<br><br>const {<br>  value: isOpen,<br>  toggle<br>} = useToggle();</pre><h4>Pattern 2— useLocalStorage</h4><p>Interview</p><p>Persist theme.</p><p>Persist cart.</p><p>Persist auth.</p><p>Hook</p><pre>import { useState } from &quot;react&quot;;<br><br>function useLocalStorage(key, initialValue) {<br>  const [value, setValue] = useState(() =&gt; {<br>    const stored = localStorage.getItem(key);<br><br>    return stored<br>      ? JSON.parse(stored)<br>      : initialValue;<br>  });<br><br>  const setStoredValue = (newValue) =&gt; {<br>    setValue(newValue);<br><br>    localStorage.setItem(<br>      key,<br>      JSON.stringify(newValue)<br>    );<br>  };<br><br>  return [value, setStoredValue];<br>}<br><br><br><br>// Usage<br><br>const [theme, setTheme] =<br>useLocalStorage(&quot;theme&quot;, &quot;light&quot;);</pre><h4>Pattern 3— useFetch</h4><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>function useFetch(url) {<br>  const [data, setData] = useState([]);<br>  const [loading, setLoading] =<br>    useState(false);<br>  const [error, setError] =<br>    useState(null);<br><br>  useEffect(() =&gt; {<br>    let ignore = false;<br><br>    async function fetchData() {<br>      try {<br>        setLoading(true);<br><br>        const response = await fetch(url);<br><br>        if (!response.ok) {<br>          throw new Error(&quot;Request failed&quot;);<br>        }<br><br>        const json = await response.json();<br><br>        if (!ignore) {<br>          setData(json);<br>        }<br>      } catch (err) {<br>        if (!ignore) {<br>          setError(err.message);<br>        }<br>      } finally {<br>        if (!ignore) {<br>          setLoading(false);<br>        }<br>      }<br>    }<br><br>    fetchData();<br><br>    return () =&gt; {<br>      ignore = true;<br>    };<br>  }, [url]);<br><br>  return {<br>    data,<br>    loading,<br>    error<br>  };<br>}<br><br><br>// Usage<br><br>const {<br>data,<br>loading,<br>error<br>}=useFetch(url);<br><br><br>Better Version (Production)<br><br>A production-ready version often adds:<br><br>AbortController<br>refetch()<br>caching<br>configurable options (headers, method, body)<br>retry support<br><br>Those can be layered onto the basic hook as needed.</pre><h4>Pattern 4 — usePagination</h4><pre>function usePagination(data, pageSize) {<br>  const [page, setPage] = useState(1);<br><br>  const totalPages = Math.ceil(<br>    data.length / pageSize<br>  );<br><br>  const currentItems = useMemo(() =&gt; {<br>    const start = (page - 1) * pageSize;<br><br>    return data.slice(start, start + pageSize);<br>  }, [data, page, pageSize]);<br><br>  return {<br>    page,<br>    setPage,<br>    totalPages,<br>    currentItems<br>  };<br>}</pre><h4>Pattern 5 — useOutsideClick</h4><pre>import { useEffect, useRef } from &quot;react&quot;;<br><br>function useOutsideClick(onClose) {<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    function handleClick(event) {<br>      if (<br>        ref.current &amp;&amp;<br>        !ref.current.contains(event.target)<br>      ) {<br>        onClose();<br>      }<br>    }<br><br>    document.addEventListener(<br>      &quot;mousedown&quot;,<br>      handleClick<br>    );<br><br>    return () =&gt; {<br>      document.removeEventListener(<br>        &quot;mousedown&quot;,<br>        handleClick<br>      );<br>    };<br>  }, [onClose]);<br><br>  return ref;<br>}<br><br>//Usage<br><br>const ref = useOutsideClick(() =&gt; {<br>  setOpen(false);<br>});<br><br>&lt;div ref={ref}&gt;</pre><h3>Next Post — Part -2</h3><p><strong>React Forms (Machine Coding + Interviews)</strong></p><p>We’ll cover:</p><ul><li>Controlled vs uncontrolled components</li><li>Generic handleChange</li><li>Dynamic forms</li><li>Validation</li><li>Error handling</li><li>Formik</li><li>React Hook Form</li><li>Multi-step forms</li><li>File upload</li><li>Dependent dropdowns</li><li>Dynamic field arrays</li><li>Optimistic submission</li><li>Common interview questions</li></ul><p>Forms are one of the most common React machine coding topics, especially for enterprise applications.</p><p>Connect with me on LinkedIn: <a href="https://www.linkedin.com/in/rahulv28/">Rahul Verma</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf1d2b1a962" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>