Repository navigation
feat(metrics): Add metrics consumer for billing [INGEST-1609] - #39236
Conversation
`TRANSACTION_METRICS_NAMES` isn't regularly updated. Setting the metric ID in the instance initialization removes unnecessary access on every `submit` call.
| if amount < 1: | ||
| return | ||
|
|
||
| track_outcome( |
There was a problem hiding this comment.
I assume calling this function here, instead of duplicating the logic, isn't a concern in terms of performance and scalability.
There was a problem hiding this comment.
What does this function do? Keep in mind this is blocking on the submit method (if it's something that can take a while). This way only one message is being processed at a time and the next message won't start until this function is done. Is that ok?
There was a problem hiding this comment.
It's this function:
sentry/src/sentry/utils/outcomes.py
Line 39 in 8753024
The function is not heavy computation-wise, so I discarded the alternative to perform the computation asynchronously.
There was a problem hiding this comment.
track_outcome calls KafkaPublisher.publish, which itself sends a Kafka message asynchronously, so I guess it's OK?
sentry/src/sentry/utils/outcomes.py
Line 108 in 8753024
sentry/src/sentry/utils/pubsub.py
Lines 74 to 75 in 58dbd38
@lynnagara what would be a better place to call this function? In self.poll(), maybe?
There was a problem hiding this comment.
Looking at track_outcome, it seems that function uses the legacy publisher to produce messages. That producer does not guarantee delivery as it does not wait for the callback. So you can loose outcomes, specifically in case of errors or when the consumer is shut down.
Is that acceptable ?
If not please use the arroyo producer instead (that returns a future) so you can wait for the future result periodically and commit only when you have confirmation the message has been produced to Kafka.
There was a problem hiding this comment.
So you can loose outcomes, specifically in case of errors or when the consumer is shut down.
Is that acceptable ?
From my current understanding, it is acceptable, but I will let @jan-auer make the final call.
There was a problem hiding this comment.
Let's go with this implementation to unblock other work, and move this to the arroyo producer in an immediate follow-up. We definitely want delivery guarantees.
|
It seems fine to me but I'm not clear on what If it's more efficient or supported, you might want to accumulate a batch in the But if that's not possible I think what you're doing makes sense in principle |
| self.__closed = False | ||
|
|
||
| def poll(self) -> None: | ||
| self._bulk_commit() |
There was a problem hiding this comment.
@lynnagara is it OK to commit on every poll, or do we need batched or throttled commits, like in
sentry/src/sentry/replays/consumers/recording/process_recording.py
Lines 249 to 256 in 6da3b22
There was a problem hiding this comment.
you cannot commit at every poll. That can happen tens of thousands of times per second. You need to batch commit after you successfully send the message.
There was a problem hiding this comment.
See
sentry/src/sentry/runner/commands/run.py
Lines 452 to 466 in f94d5af
|
The PR looks good to me, but I'm biased for having worked on it. |
| self.__closed = False | ||
|
|
||
| def poll(self) -> None: | ||
| self._bulk_commit() |
There was a problem hiding this comment.
you cannot commit at every poll. That can happen tens of thousands of times per second. You need to batch commit after you successfully send the message.
| if amount < 1: | ||
| return | ||
|
|
||
| track_outcome( |
There was a problem hiding this comment.
Looking at track_outcome, it seems that function uses the legacy publisher to produce messages. That producer does not guarantee delivery as it does not wait for the callback. So you can loose outcomes, specifically in case of errors or when the consumer is shut down.
Is that acceptable ?
If not please use the arroyo producer instead (that returns a future) so you can wait for the future result periodically and commit only when you have confirmation the message has been produced to Kafka.
| ) | ||
|
|
||
| calls = track_outcome.mock_calls | ||
| for _ in range(100): |
There was a problem hiding this comment.
I think this is going to be a fragile test as there is a waiting time every time you subscribe to a topic before you start receiving messages that depends on how long kafka takes to rebalance and assign you partitions. So 100 may be not enough in a flaky way.
Since you are mocking all the producer logic I would suggest you turn this into a test that does not depend on Kafka to be running.
Arroyo provides you three ways to test your consumer:
- unit test the processing strategy: This means instantiate
BillingTxCountMetricConsumerStrategywith the factory you created and routinely callsubmitandpoll. So you test your logic without the need of the entire Kafka scaffolding. - test your consumer with the arroyo in memory broker/consumer. This is a fake of the Kafka consumer for unit tests so the response time is predictable.
- Or you test with the real Kafka but this should be used only when you want to run integration tests.
There was a problem hiding this comment.
Converted the test to a unit test calling submit and poll on the strategy repeatedly.
|
|
||
| @run.command("billing-metrics-consumer") | ||
| @log_options() | ||
| @batching_kafka_options("billing-metrics-consumer") |
There was a problem hiding this comment.
This decorator allows the client to specify max-batch-size and max-batch-time-ms. That generally tells you how often you are supposed to commit.
There was a problem hiding this comment.
Thanks, now used by the strategy.
| self.__closed = False | ||
|
|
||
| def poll(self) -> None: | ||
| self._bulk_commit() |
There was a problem hiding this comment.
See
sentry/src/sentry/runner/commands/run.py
Lines 452 to 466 in f94d5af
| @log_options() | ||
| @batching_kafka_options("billing-metrics-consumer") | ||
| @configuration | ||
| @click.option("--topic", default="snuba-generic-metrics", help="Topic to get metrics from.") |
There was a problem hiding this comment.
You should not need to pass a topic name in the CLI and it is generally a bad practice.
You should not need it because, if you want to override the topic name, batch_kafka_options already provides you a force-topic CLI argument.
It is a bad practice because it bypasses the system that maps topics to cluster in the settings. Topics are defined as abstract entities here: https://github.com/getsentry/sentry/blob/master/src/sentry/conf/server.py#L2442-L2472 then mapped to clusters here https://github.com/getsentry/sentry/blob/master/src/sentry/conf/server.py#L2489. The idea is that you could override topic names per environment via settings. That is horribly broken because how settings work in Sentry, still if you expect the topic name to be always passed in, you would be skipping all the logic that maps topic name to cluster which is even worse.
So the right approach is to remove this field and rely on the constant from server.py as a topic name. Also use the force-topic field if, for some reason, in some specific environment there is a reason to override the topic. Should very rarely happen
There was a problem hiding this comment.
This consumer is transaction-specific, so it should be marked with the transactions/performance cogs category on deployment. Even if it runs over buckets from other categories (i.e. sessions), the reason it exists is transactions, and thus that's where the cost should be attributed to. cc @oioki
| project_id: int | ||
| metric_id: int | ||
| timestamp: int | ||
| value: Sequence[float] # only true for distribution buckets |
There was a problem hiding this comment.
Since this isn't true for all buckets observed, could we leave that untyped and introduce an explicit check, or does that increase overheads too much?
| if amount < 1: | ||
| return | ||
|
|
||
| track_outcome( |
There was a problem hiding this comment.
Let's go with this implementation to unblock other work, and move this to the arroyo producer in an immediate follow-up. We definitely want delivery guarantees.
Apply rate limits to metrics buckets from the `transactions` namespace. # Background Dynamic Sampling introduces a new type of quota, `transactions_processed`, which defines how many transactions should be "processed", i.e. whether or not we should extract metrics from them. This quota is always >= the `transactions` quota, which defines how many transactions should be stored & indexed. The new data category should not only apply to incoming transaction payloads (see #1517), but also to metrics buckets, which may have been extracted by an upstream Relay. Moreover, processing Relays must _count_ the number of transactions for which metrics have been dropped, and create outcomes for them, in the same way that we create accepted outcomes (see getsentry/sentry#39236). # Data Flow Processing Relays check rate limits against Redis. Currently the only actor that has access to this rate limiter is the `EnvelopeProcessor`, and we want to make use of its thread pool to make the blocking calls to Redis. This makes it necessary to redirect metrics buckets to the processor before sending them to the `EnvelopeManager` for publishing: ## Old Flow (still applies under certain conditions) ``` ┌──────────┐ ┌────────────┐ ┌───────────────┐ │Aggregator│ │ProjectCache│ │EnvelopeManager│ └────┬─────┘ └─────┬──────┘ └──────┬────────┘ │ │ │ │ FlushBuckets │ │ ├───────────────►│ │ │ │ SendMetrics │ │ ├──────────────►│ │ │ │ ``` ## New Flow ``` ┌──────────┐ ┌────────────┐ ┌─────────────────┐ ┌─────┐ ┌───────────────┐ │Aggregator│ │ProjectCache│ │EnvelopeProcessor│ │Redis│ │EnvelopeManager│ └────┬─────┘ └─────┬──────┘ └────────┬────────┘ └──┬──┘ └──────┬────────┘ │ │ │ │ │ │ FlushBuckets │ │ │ │ ├─────────────►│ │ │ │ │ │ RateLimitFlushBuckets │ │ │ │ ├──────────────────────►│ │ │ │ │ ├────────────►│ │ │ │ │ │ │ │ │ │◄────────────┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ SendMetrics │ │ │ ├─────────────┬──────────►│ │ │ │ │ │ ``` # Business Logic 1. ProjectCache received a `FlushBuckets` from the metrics aggregator. 2. Count the number of transactions that contributed to these buckets (see below). 2. Check if cached rate limits apply. 3. If so, drop transaction-related buckets, generate outcomes, and send the buckets to `EnvelopeManager`. 4. Otherwise, if processing mode is enabled, send buckets to the `EnvelopeProcessor`. 5. The processor communicates the transaction count to redis and applies the rate limit if reached. 6. The processor sends a message to the project cache to update the cached rate limits. 7. Drop transaction-related buckets, generate outcomes, and send the buckets to `EnvelopeManager`. ## Counting processed transactions * For `d:transactions/duration@millisecond`, increment the counter in redis by the length of the bucket's value. This is an accurate count of the number of transactions that contributed to the bucket. * For any other metric, do not increment the counter in redis, but still enforce the rate limit if the quota is currently exceeded. # Not in this PR * Enforcement of rate limits on the fast path. * Enforcements of rate limits on metrics buckets in the `sessions` namespace. Co-authored-by: Jan Michael Auer <[email protected]>
Add a consumer that reads from
snuba-metrics(the topic the metrics indexer produces to), and callstrack_outcomefor processed transactions.d:transactions/duration@millisecondis the one metric that we unconditionally extract for every transaction, so the number of elements in the bucket value corresponds to the number of transactions that contributed to the bucket of this metric. For each bucket, report this length as thequantityof the tracked outcome.Future work:
Replace the usage of
track_outcomewith a streaming consumer that awaits delivery of outcomes before committing offsets.