Class: PostHog::Rails::Logs::RateLimiter Private

Inherits:
Object
  • Object
show all
Defined in:
lib/posthog/rails/logs/rate_limiter.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Fixed-window rate limiter protecting the PostHog Logs ingestion quota from runaway log volume (PostHog Logs bills by data ingested).

Thread-safe: the counter is the one piece of shared mutable state in the logs pipeline, guarded by a mutex scoped to a counter bump.

Constant Summary collapse

WINDOW_SECONDS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ RateLimiter

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of RateLimiter.

Parameters:

  • limit (Integer)

    Maximum records allowed per WINDOW_SECONDS window.



20
21
22
23
24
25
# File 'lib/posthog/rails/logs/rate_limiter.rb', line 20

def initialize(limit)
  @limit = limit
  @mutex = Mutex.new
  @window = nil
  @count = 0
end

Instance Attribute Details

#limitInteger (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns Maximum records allowed per window.

Returns:

  • (Integer)

    Maximum records allowed per window.



17
18
19
# File 'lib/posthog/rails/logs/rate_limiter.rb', line 17

def limit
  @limit
end

Instance Method Details

#recordSymbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Records one attempt and returns the verdict.

Returns:

  • (Symbol)

    :allow when under the cap, :reject_first for the first rejection of a window (callers may emit a single notice), :reject thereafter.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/posthog/rails/logs/rate_limiter.rb', line 32

def record
  @mutex.synchronize do
    window = Process.clock_gettime(Process::CLOCK_MONOTONIC).to_i / WINDOW_SECONDS
    if window != @window
      @window = window
      @count = 0
    end
    @count += 1
    next :allow if @count <= @limit

    @count == @limit + 1 ? :reject_first : :reject
  end
end