Skip to content

Switch rate limiting template from inline to pkg/ratelimit/ #247

@adnaan

Description

@adnaan

Summary

The main.go.tmpl template currently inlines a simplified rate limiter (~80 lines) using golang.org/x/time/rate directly. This was intentional — generated apps import the published version of github.com/livetemplate/lvt, so pkg/ratelimit/ exports aren't available until the next release.

After the next release, the template should import pkg/ratelimit instead of inlining the code. Same pattern as #246 (email).

What to change

  1. internal/kits/system/multi/templates/app/main.go.tmpl: Remove inline newRateLimiter, ipLimiter, getClientIP, getEnvFloat, getEnvInt functions (~140 lines). Replace with:

    import "github.com/livetemplate/lvt/pkg/ratelimit"
    
    globalRL := ratelimit.New(appCtx,
        ratelimit.WithRate(getEnvFloat("RATE_LIMIT_RPS", 100)),
        ratelimit.WithBurst(getEnvInt("RATE_LIMIT_BURST", 200)),
        ratelimit.WithMaxIPs(getEnvInt("RATE_LIMIT_MAX_IPS", 10000)),
    )
    defer globalRL.Close()
    handler := globalRL.Middleware()(securityHeadersMiddleware(...))
  2. internal/generator/auth.go (injectAuthRateLimiter): Update injected code to use ratelimit.New with ratelimit.WithDenyHandler instead of inline newRateLimiter.

  3. getEnvFloat/getEnvInt: These are still needed for reading env vars. Keep them inline or extract to a small pkg/envutil.

Benefits

  • Generated apps get sharded rate limiting (reduced lock contention under load)
  • Eviction logging via slog
  • Proper Close() with goroutine lifecycle management
  • Bug fixes to the library automatically benefit all new apps
  • ~140 fewer lines of generated code

Context

Introduced in the rate limiting PR. The inline version is a single-mutex-only copy of the library's algorithm, lacking sharding, eviction logging, and configurable sweep/stale intervals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    follow-upFollow-up task from PR review

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions