Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion .github/workflows/benchmark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,19 @@ jobs:
- name: Run benchmark
run: erl -noshell -pa $(./rebar3 path --lib)/imetrics/benchmarks -pa $(./rebar3 path) -s imetrics_sparse_write_benchmark -eval 'init:stop().'

- name: Run contended write benchmark
run: erl -noshell -pa $(./rebar3 path --lib)/imetrics/benchmarks -pa $(./rebar3 path) -s imetrics_contended_write_benchmark -eval 'init:stop().'

- name: Run write scaling benchmark
run: erl -noshell -pa $(./rebar3 path --lib)/imetrics/benchmarks -pa $(./rebar3 path) -eval 'imetrics_write_scaling_benchmark:start(), init:stop().'

- name: Download previous benchmark data
uses: actions/cache@v4
with:
path: ./cache
key: ${{ runner.os }}-benchmark

- name: Track benchmark in GH comments
- name: Track response time in GH comments
uses: benchmark-action/github-action-benchmark@v1.20.4
with:
tool: "customSmallerIsBetter"
Expand All @@ -40,3 +46,36 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
comment-on-alert: true
summary-always: true

- name: Track write throughput in GH comments
uses: benchmark-action/github-action-benchmark@v1.20.4
with:
name: Write throughput
tool: "customBiggerIsBetter"
output-file-path: "benchmark_results_throughput.json"
external-data-json-path: ./cache/benchmark-throughput-data.json
github-token: ${{ secrets.GITHUB_TOKEN }}
comment-on-alert: true
summary-always: true

- name: Track contended write benchmark in GH comments
uses: benchmark-action/github-action-benchmark@v1.20.4
with:
name: Contended write benchmark
tool: "customBiggerIsBetter"
output-file-path: "benchmark_results_contended.json"
external-data-json-path: ./cache/benchmark-contended-data.json
github-token: ${{ secrets.GITHUB_TOKEN }}
comment-on-alert: true
summary-always: true

- name: Track write scaling benchmark in GH comments
uses: benchmark-action/github-action-benchmark@v1.20.4
with:
name: Write scaling benchmark
tool: "customBiggerIsBetter"
output-file-path: "benchmark_results_scaling.json"
external-data-json-path: ./cache/benchmark-scaling-data.json
github-token: ${{ secrets.GITHUB_TOKEN }}
comment-on-alert: true
summary-always: true
66 changes: 61 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Dependencies
------------

- *No R16 support*: We require the "newer" ets functions such as ets:update_counter/4.
- *OTP 25 or later*: tables are created with `{write_concurrency, auto}`, which older releases reject.
- *cowboy*: The `cowboy` application (and its dependencies) must be started before you start `imetrics`
- `cowboy` depends on `ranch`, `cowlib`, `ssl`, and `crypto` [(see here)](https://ninenines.eu/docs/en/cowboy/2.8/manual/)

Expand Down Expand Up @@ -113,6 +114,10 @@ imetrics_hist_openmetrics:new(http_response_time, [0, 0.01, 0.05, 0.1, 0.2, 1, 1
imetrics_hist_openmetrics:new(packet_size, [0, 1000], 251).
```

Calling `new` again for an existing histogram (the same name and tags) resets its counts to zero. The
reset is not atomic with concurrent observations: an `add` running at the same time may be counted in the
reset histogram or lost.

Histograms are incremented by indicating a continuous value, which will add one to the bucket in which that value would fall.

```erlang
Expand Down Expand Up @@ -157,8 +162,10 @@ Finally, exemplars can attach a timestamp. If left undefined, the timestamp will
Timestamps should be in seconds from Unix Epoch, and do not need to be integers.
If exemplars are not updated between queries, additional copies of the exemplar will not be generated,
so creating exemplars on infrequent events will not result in overpopulation of the data set.
Additionally, whenever `set_exemplar` is called, the previous exemplar associated with the given
name and tags will be overwritten, meaning only the most recently passed exemplar will be stored at any given time.
Additionally, only the most recent exemplar for a given name and tags is reported: exemplars are
stored per scheduler (see [Concurrency](#concurrency)), and reads return the one with the newest timestamp.
If you pass timestamps yourself, an exemplar set later with an older timestamp is not reported while a newer
one exists on another scheduler. If two exemplars have the same timestamp, either may be reported.
`imetrics:set_exemplar`, when called without a type identifier, or when called with a type of `counter`, does not check to see if the added exemplar is associated with any actual values, and will always return true. `imetrics_hist_openmetrics:set_exemplar`, or `imetrics:set_exemplar` with type `histogram`, works slightly differently, in that the value provided for the exemplar determines which bucket it is associated with in the histogram, and if the function is called for a histogram/tag combination that does not exist, this function will return `{error, {badarg, check_ets}}`.
```erlang
%Minimal set_exemplar
Expand Down Expand Up @@ -221,8 +228,8 @@ a map of tag permutations, with the value corresponding to each tag permutation.
> imetrics:get_with_types().
[{<<"client_connections">>,{counter,[{#{},1}]}},
{<<"http_responses">>,
{counter,[{#{code => <<"404">>},1},
{#{code => <<"200">>},1}]}},
{counter,[{#{code => <<"200">>},1},
{#{code => <<"404">>},1}]}},
{<<"cpu_load_avg">>,
{gauge,[{#{granularity => <<"1min">>},0.1},
{#{granularity => <<"5min">>},3.4}]}},
Expand All @@ -239,8 +246,8 @@ $ curl localhost:8085/metrics
# TYPE client_connections counter
client_connections_total{} 1
# TYPE http_responses counter
http_responses_total{code="404"} 1
http_responses_total{code="200"} 1
http_responses_total{code="404"} 1
# TYPE cpu_load_avg gauge
cpu_load_avg{granularity="1min"} 0.1
cpu_load_avg{granularity="5min"} 3.4
Expand Down Expand Up @@ -301,3 +308,52 @@ Configuration
| `strict_openmetrics_compat` | `false` | If set to `true`, metrics will only display on the old HTTP endpoint if they aren't compatible with the OpenMetrics endpoint. Metrics will only display on one endpoint or the other, never both. |
| `openmetrics_exemplar_compat` | `false` | If set to `true`, counters will display with _total appended to their end, and exemplars will be displayed for counters. When `false`, counters will not get the appended suffix, and exemplars will not be displayed on counters. |
| `hist_max_buckets` | `64` | Upper limit on the number of buckets for histograms. Calls to create a histogram with more buckets than this value will fail. |

Concurrency
-----------

Counter and histogram writes are sharded by scheduler: each counter series and
histogram bucket is stored as up to `erlang:system_info(schedulers)` ETS rows,
keyed by the writing scheduler's id, and every read sums the shards. Concurrent
writes to the same metric therefore don't serialize on one ETS row lock.

Because of this, `imetrics:add/1,2,3` and `imetrics:add_m/2,3` return the
calling scheduler's shard value after the increment, not the counter's total,
and `imetrics_hist_openmetrics:add/2,3` returns `{Bucket, ShardCount}`. Read
totals with `imetrics:get_counters/0`, `imetrics:get_with_types/0`,
`imetrics_hist_openmetrics:get_hist/1,2` or the HTTP endpoints. Exemplars are
sharded the same way, and `imetrics:get_exemplar/1` returns the one with the
newest timestamp across the shards; `imetrics:get_exemplars/0` returns every
exemplar that way in one scan, as a map keyed like `get_exemplar/1`. Gauges are
not sharded.

### Trade-offs ###

- **Callers that used the return value of `add`.** A caller that treated the
result of `add`/`add_m` as the counter's total, or the second element of a
histogram `add` as the bucket's total, now silently gets a smaller number
instead of an error. Check for such uses when upgrading.
- **Reads cost more.** Every read sums up to one row per scheduler for each
series, so the cost of a scrape grows with series × schedulers. This is
negligible for a scraper such as Prometheus, but it shows on machines with
more cores and many series. A full read, through
`get_counters/0`, `get_with_types/0`, `get_hist/0` or `/metrics`, scans each
table once; `imetrics_hist_openmetrics:get_hist/1,2` and
`imetrics:get_exemplar/1` instead look up one row per scheduler. Application
code calling any of these in a hot path pays that cost on every call.
- **Memory grows the same way.** A counter series, histogram bucket or
exemplar written from many schedulers can take up to one ETS row per
scheduler instead of one row in total. Measured on OTP 25 (64-bit), a shard
row takes roughly 200–400 bytes for a counter or histogram bucket, depending
on how many tags it has, and about 500 bytes for an exemplar with two labels.
For example, 1,000 counter series written from all 32 schedulers of a machine
take about 7–13 MB, where unsharded they took well under 1 MB. This matters
mostly for high-cardinality counters on machines with many cores.
- **Point order.** Points within a counter, in `get_with_types/0` and on
`/metrics`, now come out sorted by tags instead of in ETS hash order. The
order was never guaranteed, but output diffs between versions will show
lines moving.
- **ETS layout.** imetrics' ETS tables are internal. Counter and exemplar keys
now include the scheduler id, and histogram counts moved to
`imetrics_hist_counts`, so code reading the tables directly must switch to
the getters.
151 changes: 151 additions & 0 deletions benchmarks/imetrics_contended_write_benchmark.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
%% @doc This benchmark models heavy contention on a single key.
%%
%% It spawns one worker process per scheduler, and every worker hammers the
%% same counter and the same histogram bucket as fast as it can. This is the
%% opposite of imetrics_sparse_write_benchmark, where each worker has its own
%% series: here all writers want the same ETS row, so throughput shows how well
%% the metric types scale with concurrent writers.
%%
%% When it finishes it checks that no increment was lost: the counter total
%% must equal the number of adds the workers made.
-module(imetrics_contended_write_benchmark).

-export([start/0]).

-define(WorkerProcesses, erlang:system_info(schedulers)).
-define(BatchSize, 100). % writes between checks for a message
-define(WarmPeriod, timer:seconds(5)).
-define(CollectPeriod, timer:seconds(30)).
-define(TimeUnit, microsecond).

-define(Counter, contended_write_benchmark_counter).
-define(Hist, contended_write_benchmark_hist).

start() ->
application:stop(imetrics),
application:set_env(imetrics, http_server_port, 0), % automatically configure the port
application:ensure_all_started(imetrics),

% create the metrics
imetrics:add(?Counter, 0),
imetrics_hist_openmetrics:new(?Hist, [1, 10]),

% create a metrics publishing workload, all writing the same keys
WorkerPids = start_worker_threads(?WorkerProcesses, []),
WorkerMon = [ erlang:monitor(process, Pid) || Pid <- WorkerPids ],

% run the workload in the "warmup" period
io:format("Warming up (waiting ~p ms)~n", [?WarmPeriod]),
[ erlang:send(Pid, start) || Pid <- WorkerPids ],
timer:sleep(?WarmPeriod),

% start collecting data
io:format("Gathering stats (waiting ~p ms)~n", [?CollectPeriod]),
[ erlang:send(Pid, collect) || Pid <- WorkerPids ],
timer:sleep(?CollectPeriod),

% send the request for the workers to send their data
io:format("Stopping test~n~n", []),
Self = self(),
WorkerRefs = [ begin
Ref = make_ref(),
erlang:send(Pid, {stop, Self, Ref}),
Ref
end || Pid <- WorkerPids ],

% collect the data
WriteData = receive_data(WorkerRefs, []),

% make sure all processes exited correctly and output our report
receive_downs(WorkerMon),
output_report(WriteData).

start_worker_threads(0, Acc) ->
Acc;
start_worker_threads(N, Acc) ->
Pid = spawn_link(fun() -> worker_loop(idle, nocollect, {0, 0, 0, 0}) end),
start_worker_threads(N-1 , [Pid|Acc]).

%% State is {StartTime, EndTime, CollectedWrites, TotalWrites}. Writes are
%% counted in pairs: one counter add and one histogram add.
worker_loop(idle, Collect, State) ->
receive
start ->
worker_loop(start, Collect, State);
collect ->
worker_loop(idle, collect, State)
end;
worker_loop(start, Collect, {StartTime, EndTime, Count, Total}) ->
write_batch(?BatchSize),
Total2 = Total + ?BatchSize,
Count2 = case Collect of
nocollect -> Count;
collect -> Count + ?BatchSize
end,
receive
{stop, From, Ref} ->
erlang:send(From, {Ref, {StartTime, erlang:monotonic_time(?TimeUnit), Count2, Total2}});
collect ->
worker_loop(start, collect, {erlang:monotonic_time(?TimeUnit), EndTime, Count2, Total2})
after 0 ->
worker_loop(start, Collect, {StartTime, EndTime, Count2, Total2})
end.

write_batch(0) ->
ok;
write_batch(N) ->
imetrics:add(?Counter),
imetrics_hist_openmetrics:add(?Hist, 5),
write_batch(N - 1).

receive_data([], Acc) ->
Acc;
receive_data([Ref|Refs], Acc) ->
receive
{Ref, DataItem} ->
receive_data(Refs, [DataItem|Acc])
end.

receive_downs([]) ->
ok;
receive_downs([M|Rest]) ->
receive
{'DOWN', M, process, _Pid, _Reason} ->
receive_downs(Rest)
end.

output_report(WriteData) ->
PerWorker = [ Count / ((EndTime - StartTime) / 1_000_000) || {StartTime, EndTime, Count, _Total} <- WriteData ],
TotalThroughput = lists:sum(PerWorker),
Expected = lists:sum([ Total || {_, _, _, Total} <- WriteData ]),
Counted = proplists:get_value(atom_to_binary(?Counter), imetrics:get_counters()),
HistBuckets = imetrics_hist_openmetrics:get_hist(?Hist),
{_, HistCount} = lists:last(HistBuckets), % the +Inf bucket is cumulative

io:format("== Write benchmark (single contended key) ==~n~n"),

io:format("Processes = ~p~n", [?WorkerProcesses]),
io:format("Writes per op = 1 counter add + 1 histogram add~n~n"),

io:format("Throughput = ~p ops/s (sum of workers)~n", [TotalThroughput]),
io:format("Per worker = ~p ops/s (avg)~n~n", [TotalThroughput / ?WorkerProcesses]),

io:format("== Integrity ==~n~n"),
io:format("Expected writes = ~p~n", [Expected]),
io:format("Counter total = ~p~n", [Counted]),
io:format("Histogram total = ~p~n~n", [HistCount]),

io:format("=====================~n~n"),

{ok, File} = file:open("./benchmark_results_contended.json", [write]),
io:format(File, "[~n", []),
io:format(File, "{\"name\": \"Contended ops throughput (sum of workers)\", \"unit\": \"ops/second\", \"value\": ~p},~n", [TotalThroughput]),
io:format(File, "{\"name\": \"Contended ops throughput (avg per worker)\", \"unit\": \"ops/second\", \"value\": ~p}~n", [TotalThroughput / ?WorkerProcesses]),
io:format(File, "]~n", []),
file:close(File),

% a lost update means the contended write path is broken
case {Counted, HistCount} of
{Expected, Expected} -> ok;
_ -> erlang:error({lost_updates, #{expected => Expected, counter => Counted, histogram => HistCount}})
end.
13 changes: 10 additions & 3 deletions benchmarks/imetrics_sparse_write_benchmark.erl
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,16 @@ output_report(WriteData, ReadData) ->

io:format("=====================~n~n"),

% one file per direction, since github-action-benchmark treats a file as
% either "smaller is better" or "bigger is better"
{ok, File} = file:open("./benchmark_results.json", [write]),
io:format(File, "[~n", []),
io:format(File, "{\"name\": \"HTTP Response Time (avg)\", \"unit\": \"microseconds\", \"value\": ~p},~n", [HttpSum / HttpSamples]),
io:format(File, "{\"name\": \"Metrics throughput (avg between workers)\", \"unit\": \"metrics/second\", \"value\": ~p}~n", [WorkerSum / ?WorkerProcesses]),
io:format(File, "{\"name\": \"HTTP Response Time (avg)\", \"unit\": \"microseconds\", \"value\": ~p}~n", [HttpSum / HttpSamples]),
io:format(File, "]~n", []),
file:close(File).
file:close(File),

{ok, ThroughputFile} = file:open("./benchmark_results_throughput.json", [write]),
io:format(ThroughputFile, "[~n", []),
io:format(ThroughputFile, "{\"name\": \"Metrics throughput (avg between workers)\", \"unit\": \"metrics/second\", \"value\": ~p}~n", [WorkerSum / ?WorkerProcesses]),
io:format(ThroughputFile, "]~n", []),
file:close(ThroughputFile).
Loading
Loading