Skip to content

Goroutine Leak in RateLimitMiddleware #144

@Bhup-GitHUB

Description

@Bhup-GitHUB

🛠️ Rate Limiter Cleanup Goroutine Never Stops During Graceful Shutdown

❗ Problem Summary

The RateLimitMiddleware starts a background cleanup goroutine inside NewRateLimitMiddleware() (line 49 in internal/restapi/rate_limit_middleware.go). However, this goroutine never stops, even during a graceful shutdown, causing a goroutine leak.


🔍 Details

1. Goroutine Starts but Never Ends

// internal/restapi/rate_limit_middleware.go:49
go middleware.cleanup() // Runs forever

This launches a cleanup loop that continues running even after the server shuts down.


2. A Stop Method Exists (But Is Never Called)

// internal/restapi/rate_limit_middleware.go:174-179
func (rl *RateLimitMiddleware) Stop() {
    if rl.cleanupTick != nil {
        rl.cleanupTick.Stop()
    }
}

The cleanup ticker can be stopped — but nothing ever calls this method.


3. Root Cause

The RestAPI struct only stores middleware handlers, not the actual RateLimitMiddleware instance.

As a result, cmd/api/app.go has no reference to the middleware, so it cannot call Stop() during shutdown.

This prevents graceful cleanup of the goroutine.


🚨 Impact

  • Goroutine leaks
  • Cleanup ticker continues running after shutdown
  • Incomplete graceful shutdown
  • Unnecessary resource usage

✅ Proposed Fix

  1. Modify RestAPI to store a reference to the RateLimitMiddleware instance.
  2. During shutdown, call rateLimiter.Stop() (similar to gtfsManager.Shutdown()).
  3. Ensure the cleanup goroutine exits when the ticker stops.

This ensures a clean, leak-free shutdown.


🙋 I Would Love to Work on This!

I'm interested in implementing this fix and improving the shutdown behavior of the rate-limiter middleware.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions