Skip to content

feat(metrics): Add metrics consumer for billing [INGEST-1609] - #39236

Merged
jjbayer merged 37 commits into
masterfrom
iker/feat/billing-metrics-consumer
Oct 4, 2022
Merged

jjbayer merged 37 commits into
masterfrom
iker/feat/billing-metrics-consumer

Conversation

@iker-barriocanal

@iker-barriocanal iker-barriocanal commented Sep 23, 2022 •

Copy link
Copy Markdown
Contributor

Add a consumer that reads from snuba-metrics (the topic the metrics indexer produces to), and calls track_outcome for processed transactions.

d:transactions/duration@millisecond is 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 the quantity of the tracked outcome.

Future work:

Replace the usage of track_outcome with a streaming consumer that awaits delivery of outcomes before committing offsets.

@iker-barriocanal iker-barriocanal self-assigned this Sep 23, 2022
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Sep 23, 2022
if amount < 1:
return

track_outcome(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume calling this function here, instead of duplicating the logic, isn't a concern in terms of performance and scalability.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's this function:

def track_outcome(

The function is not heavy computation-wise, so I discarded the alternative to perform the computation asynchronously.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

track_outcome calls KafkaPublisher.publish, which itself sends a Kafka message asynchronously, so I guess it's OK?

publisher.publish(

if self.asynchronous:
self.producer.poll(0)

@lynnagara what would be a better place to call this function? In self.poll(), maybe?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @onewland, this should be cheap.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@onewland

Copy link
Copy Markdown
Contributor

It seems fine to me but I'm not clear on what track_outcome does underneath the hood.

If it's more efficient or supported, you might want to accumulate a batch in the submit method and then do an expensive track_outcome[s] on that batch in the join.

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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lynnagara is it OK to commit on every poll, or do we need batched or throttled commits, like in

def __throttled_commit(self, force: bool = False) -> None:
now = time.time()
if (now - self.__last_committed) >= COMMIT_FREQUENCY_SEC or force is True:
if self.__commit_data:
self.__commit(self.__commit_data)
self.__last_committed = now
self.__commit_data = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See

f = click.option(
"--max-batch-size",
"max_batch_size",
default=100,
type=int,
help="How many messages to process before committing offsets.",
)(f)
f = click.option(
"--max-batch-time-ms",
"max_batch_time",
default=1000,
type=int,
help="How long to batch for before committing offsets.",
)(f)
to decide how often to commit.

@iker-barriocanal

Copy link
Copy Markdown
Contributor Author

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 BillingTxCountMetricConsumerStrategy with the factory you created and routinely call submit and poll. 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, now used by the strategy.

self.__closed = False

def poll(self) -> None:
self._bulk_commit()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See

f = click.option(
"--max-batch-size",
"max_batch_size",
default=100,
type=int,
help="How many messages to process before committing offsets.",
)(f)
f = click.option(
"--max-batch-time-ms",
"max_batch_time",
default=1000,
type=int,
help="How long to batch for before committing offsets.",
)(f)
to decide how often to commit.

Comment thread src/sentry/runner/commands/run.py Outdated
@log_options()
@batching_kafka_options("billing-metrics-consumer")
@configuration
@click.option("--topic", default="snuba-generic-metrics", help="Topic to get metrics from.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I removed the option.

@jan-auer jan-auer left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

if amount < 1:
return

track_outcome(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jjbayer
jjbayer merged commit 5399ff9 into master Oct 4, 2022
@jjbayer
jjbayer deleted the iker/feat/billing-metrics-consumer branch October 4, 2022 12:47
jjbayer added a commit to getsentry/relay that referenced this pull request Oct 17, 2022
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]>
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 19, 2022

This branch was successfully deployed

2 active deployments
Preview – storybook — d30521fc Deployed Oct 4, 2022 by vercel[bot]
Preview – sentry — d30521fc Deployed Oct 4, 2022 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants