Video summary

Golang Microservices Full Course #14 - Rate Limit & JWT Blacklist

Main summary

Key takeaways

Technology

Course focus (Golang microservices): Rate limiting + JWT blacklist

This lesson extends the existing Golang microservices project by adding:

  1. Redis-backed API rate limiting (to prevent brute-force/abuse)
  2. JWT blacklist on logout (to revoke tokens early by storing them in Redis)

Prior setup mentioned (testing + Redis mocks)

  • Updates service tests to include RDB/Redis mocks (e.g., transaction service and wallet service tests).
  • Uses mock Redis expectations like Get, Set, Delete / Expect delete.
  • Adds a sleep to allow async goroutines (for Redis-related async invalidation) to finish.
  • Ensures wallet service tests use a logger to avoid prior test errors.

1) Rate limiting (Redis sliding window–style)

Goal

Secure APIs from brute force and abuse attacks.

Mechanism described

  • Track request counts per IP (or user identifier) in Redis.
  • Key format concept: rate_limit_<ip>_<time-window>
  • “Sliding window” behavior is described as:
    • Max number of requests per minute (example: 60 requests per minute per IP).
  • If the Redis counter exceeds the configured limit:
    • Return HTTP 429 Too Many Requests.

Implementation plan (middleware)

  • Create middleware file: middleware/rate_limiter.go
  • Middleware signature:
    • func rateLimiter(rdb ..., limit int, window time.Duration) gin.HandlerFunc
  • Use a Redis pipeline to atomically:
    • INCR the request counter key
    • EXPIRE it (TTL set to window * 2 as a safety margin)
  • Logic:
    • If counter > limit → abort request and return a custom error (429 “Too Many Requests / rate limit exceeded”)
    • Else → c.next()

2) JWT blacklist (logout revocation using Redis)

Problem addressed

  • JWTs are stateless by default (valid until expiration).
  • If a user logs out, a stolen token could still be used.

Solution

  • Blacklist the JWT in Redis on logout.

Mechanism described

  • On logout:
    • Compute timeLeft until token expiration.
    • Store the token in Redis blacklist key:
      • Key concept: blacklist_jwt_<token>
      • TTL concept: store until timeLeft (so blacklist entry expires)
  • During request authentication:
    • Check if token exists in Redis blacklist.
    • If blacklisted → return HTTP 401 Unauthorized (course notes also reference “Gone”-style wording such as 404/410 “Gone” in subtitles, but the final revoke messaging aligns with unauthorized/logout revocation).
    • Message concept: “Login session has ended / please login again”.

Middleware changes for JWT blacklist

  • Add blacklist checking inside authentication middleware (token parsing/validation flow).
  • Use Redis EXISTS to detect if the token is blacklisted.
  • If blacklisted:
    • abort request
    • return custom unauthorized error (token revoked / login session ended)

Service + handler additions (logout implementation)

User service logout

  • Create a Logout method in the user service:
    • Validate token claims
    • Calculate timeLeft from exp
    • If token already expired: no need to blacklist
    • Else:
      • write token into Redis blacklist with TTL (timeLeft)

Need for RDB injection

  • Middleware and service must receive rdb / Redis client (subtitles emphasize adding RDB in the right places).

User handler logout endpoint

  • Implement handler:
    • reads token (from request context)
    • calls svc.logout
    • returns a JSON success response like:
      • “token session deactivated / logout successful”

Main server wiring (Gin)

  • Add global rate limiter middleware in main.go:
    • Example config: Max 60 requests per minute per IP
  • Add a new protected route:
    • POST /user/logout (protected; requires authentication)

Swagger/testing workflow

  • Run the server and open:
    • Swagger UI at localhost (swagger index.html)
  • Test logout flow:
    • First logout without/with invalid token → expected error (“invalid token / missing token”)
    • Login then logout → expected success:
      • “Logout successful”
      • token session deactivated
    • After logout, attempts like accessing wallet should yield:
      • “login session has ended / please log in again”

Unit test status + gaps

  • go test is run; many test files were added earlier.
  • Instructor notes logout unit tests were not covered yet and should be added.
  • A “rate limiting testing” gap is explicitly left:
    • Instructor asks to add or research rate limiter tests (e.g., “Google it or leave it first”).
  • Some logout tests initially failed; adjustments were made, but the final message indicates rate limiting tests still needed.

Source / main speakers (from subtitles)

  • Primary instructor/author: The course presenter (“back again to this course…”)
  • Secondary source: Auto-generated coding/AI assistant output mentioned in subtitles (“created by an AI … should be okay…”).

Rate this summary

Your feedback will help improve summaries.

Improve this summary

Reprocess with a stronger model when the summary feels incomplete or inaccurate.

Pro

Translate summary in another language

Pro

Ask questions to this video

Chat for follow-up questions, clarifications, and source-backed answers.

Coming soon

Share this summary

Original video