# CloudWatch Floci supports both CloudWatch Logs and CloudWatch Metrics. --- ## CloudWatch Logs **Protocol:** JSON 1.1 (`X-Amz-Target: Logs.*`) **Endpoint:** `POST http://localhost:4566/` ### Supported Actions | Action | Description | |---|---| | `CreateLogGroup` | Create a log group | | `DeleteLogGroup` | Delete a log group | | `PutLogGroupDeletionProtection` | Enable or disable deletion protection for a log group by name or ARN | | `DescribeLogGroups` | List log groups | | `CreateLogStream` | Create a log stream inside a log group | | `DeleteLogStream` | Delete a log stream | | `DescribeLogStreams` | List log streams in a group | | `PutLogEvents` | Write log events to a stream | | `GetLogEvents` | Read log events from a stream | | `FilterLogEvents` | Search log events with a filter pattern | | `PutRetentionPolicy` | Set log retention (days) | | `DeleteRetentionPolicy` | Remove log retention policy | | `AssociateKmsKey` | Associate a KMS key with a log group (`logGroupName` or `resourceIdentifier`) | | `DisassociateKmsKey` | Remove a log group's KMS key association | | `TagLogGroup` | Tag a log group | | `UntagLogGroup` | Remove tags | | `ListTagsLogGroup` | List tags | | `TagResource` | Tag a log group, cross-account destination, delivery source, delivery destination or delivery by ARN | | `UntagResource` | Remove tags from a log group, cross-account destination, delivery source, delivery destination or delivery by ARN | | `ListTagsForResource` | List tags for a log group, cross-account destination, delivery source, delivery destination or delivery ARN | | `PutSubscriptionFilter` | Create or update a subscription filter (see [Subscription filters](#subscription-filters)) | | `DescribeSubscriptionFilters` | List subscription filters on a log group | | `DeleteSubscriptionFilter` | Delete a subscription filter | | `PutMetricFilter` | Create or replace a metric filter on a log group (see [Metric filters](#metric-filters)) | | `DescribeMetricFilters` | List metric filters by log group and name prefix, or by metric name and namespace | | `DeleteMetricFilter` | Delete a metric filter | | `TestMetricFilter` | Run a filter pattern over sample messages and return the matches with their extracted values | | `PutResourcePolicy` | Create or update an account-level (`policyName`) or log-group-scoped (`resourceArn`) resource policy; a scoped policy gets a generated name and a `revisionId`, and `expectedRevisionId` is required to update an existing scoped policy and refused on its first create (`InvalidParameterException`); a scoped put for a log group that does not exist is `ResourceNotFoundException`, and deleting a log group deletes its scoped policy; each policy reports its `policyScope` | | `DescribeResourcePolicies` | List account-level resource policies, or log-group-scoped ones with `policyScope=RESOURCE`; `resourceArn` narrows the list to that log group and is an `InvalidParameterException` unless `policyScope` is `RESOURCE`, and an unknown `policyScope` is an `InvalidParameterException` | | `DeleteResourcePolicy` | Delete an account-level policy by `policyName`, or a scoped policy by `resourceArn` with its current `expectedRevisionId`. A superseded revision answers `OperationAbortedException`; an id Floci never issued answers `InvalidParameterException` (`Invalid ExpectedRevisionId`), as on `PutResourcePolicy` | | `PutDestination` | Create or update a cross-account subscription destination, with optional tags on creation | | `PutDestinationPolicy` | Create or update the access policy for a destination | | `PutAccountPolicy` | Create or update an account-level Logs policy | | `DescribeAccountPolicies` | List account-level Logs policies by type and optional name | | `GetDataProtectionPolicy` | Return the resolved log group identifier (see note below) | | `StartQuery` | Start a Logs Insights query (see [Logs Insights](#logs-insights)) | | `GetQueryResults` | Get the status and results of a Logs Insights query | | `StopQuery` | Stop a query that has not completed yet | | `PutQueryDefinition` | Create or replace a saved Logs Insights query definition | | `DescribeQueryDefinitions` | List saved queries, with name prefix and query language filters and pagination | | `DeleteQueryDefinition` | Delete a saved query definition by ID | | `PutDeliverySource` | Create or replace a vended-log delivery source (see [Vended log delivery](#vended-log-delivery)) | | `GetDeliverySource` | Return a delivery source | | `DeleteDeliverySource` | Delete a delivery source no delivery uses | | `DescribeDeliverySources` | List delivery sources, optionally only those for given resource ARNs | | `PutDeliveryDestination` | Create or replace a delivery destination: a log group, S3 bucket, Firehose stream or X-Ray | | `GetDeliveryDestination` | Return a delivery destination | | `DeleteDeliveryDestination` | Delete a delivery destination no delivery uses | | `DescribeDeliveryDestinations` | List delivery destinations, optionally only those with given names | | `CreateDelivery` | Pair a delivery source with a delivery destination | | `GetDelivery` | Return a delivery, with its record fields and S3 configuration | | `UpdateDeliveryConfiguration` | Change a delivery's record fields, delimiter or S3 configuration | | `DeleteDelivery` | Delete a delivery | | `DescribeDeliveries` | List deliveries, optionally only those from given delivery sources | `DescribeLogGroups` returns names in ASCII order, with up to 50 groups per page by default. Set `limit` to an integer from 1 to 50 and pass the returned `nextToken` with the same region and name prefix to continue. The final page omits `nextToken`. `CreateLogGroup` stores `logGroupClass` as `STANDARD` (the default), `INFREQUENT_ACCESS`, or `DELIVERY`. `DescribeLogGroups` returns the stored class and applies an optional `logGroupClass` filter before pagination. Continue with the same class filter when using `nextToken`. Stored groups without a class default to `STANDARD`. Class metadata does not change retention, delivery behavior, or the features available on a group. Log group deletion protection defaults to disabled and is persisted with the log group. When it is enabled, `DeleteLogGroup` returns `ValidationException` until protection is explicitly disabled with `PutLogGroupDeletionProtection`. One action is currently simplified: - **`GetDataProtectionPolicy`** does not model data-protection policies. It returns HTTP 200 with the resolved `logGroupIdentifier` and no `policyDocument`, including for a log group that does not exist, where real AWS returns `ResourceNotFoundException`. `FilterLogEvents` reads `filterPattern` with the filter pattern syntax described below, the one metric filters and subscription filters use: terms, quoted phrases, `?` alternatives, `-` exclusions, JSON and space-delimited patterns. An invalid pattern is refused with `InvalidParameterException`, and so is a request that names no log group by `logGroupName` or `logGroupIdentifier`. ### Saved query definitions `PutQueryDefinition`, `DescribeQueryDefinitions`, and `DeleteQueryDefinition` store and manage saved Logs Insights queries, including the metadata used by Terraform's `aws_cloudwatch_query_definition`. Definitions are isolated by account and region and use the configured CloudWatch Logs storage mode, including persistence across restarts. Create a definition with `name` and `queryString`; pass its returned `queryDefinitionId` to update it. Updates replace the definition, so omitting `logGroupNames` or `parameters` clears those lists. `queryLanguage` defaults to `CWLI`; `SQL` and `PPL` are also stored as metadata. Query parameters are supported for `CWLI` definitions. Saving a definition does not execute or validate its query syntax, and does not extend the query execution subset described below. Log group names can be saved before their groups exist. `clientToken` retries are scoped to the account and region and retain the original request and returned ID independently of later updates. Repeating that request returns the same ID without overwriting newer content; reusing its token with different input returns `InvalidParameterException`. Floci retains these records until emulator reset, including after the definition is deleted, so a delayed retry cannot recreate a deleted definition. They use the same storage mode as definitions. During reset, saves and deletes return `ServiceUnavailableException` until the reset hooks resume writes. `DescribeQueryDefinitions` accepts `queryDefinitionNamePrefix`, `queryLanguage`, and `maxResults` from 1 to 1000. Pass the returned `nextToken` with the same account, region, and filters for the next page; the final page omits it. Tokens expire after 24 hours or an emulator restart. Updating or deleting an unknown definition returns `ResourceNotFoundException`. ### Vended log delivery {#vended-log-delivery} Delivery sources, delivery destinations and the deliveries that pair them, which Terraform's `aws_cloudwatch_log_delivery_source`, `aws_cloudwatch_log_delivery_destination` and `aws_cloudwatch_log_delivery` manage, for example for an EventBridge bus's logs. Floci stores the configuration and does not deliver the source's logs. - `PutDeliverySource` and `PutDeliveryDestination` create the resource or replace every parameter of an existing one. A source reports the service of its resource's ARN (`events` for an event bus) and the `logType` it was given. - A destination's `deliveryDestinationType` follows from its resource's ARN: `CWL` for a log group, `S3` for a bucket, `FH` for a Firehose stream. Only an X-Ray destination, which has no resource, names its type. - `CreateDelivery` needs an existing source and destination, and one delivery per pair; a second is `ConflictException`. Its id is 16 letters and digits. For an EventBridge event bus source, `recordFields` defaults to the bus's ten template fields and `s3DeliveryConfiguration` to the `{region}/{yyyy}/{MM}/{dd}/{HH}/` suffix path, as AWS reports them. `GetDelivery` returns those; `DescribeDeliveries` leaves them out, as AWS does. - A source or destination a delivery uses cannot be deleted (`ConflictException`). - Tags are set on create and through `TagResource`, `UntagResource` and `ListTagsForResource` on the resource's ARN; the Get and Describe responses carry none, as on AWS. - `DescribeDeliverySources` narrows to `resourceArns`, `DescribeDeliveryDestinations` to `names` and `DescribeDeliveries` to `deliverySourceNames`; a name that matches nothing is left out, not an error. - Requests are checked against the Logs API model's lengths, patterns, enums and required members, with AWS's `ValidationException` wording, for example "1 validation error detected: Value at 'limit' failed to satisfy constraint: Member must have value less than or equal to 50". - An unknown name or id is `ResourceNotFoundException`, "Requested Delivery Source does not exist in this account." (likewise for a Delivery Destination and a Delivery). - With IAM enforcement on, each action is authorized on the resources the AWS Service Authorization Reference lists for it: the source, destination or delivery it names, and for `CreateDelivery` the source, the destination and the new delivery; `DeleteDeliverySource` on the delivery destinations the deliveries from the source it deletes send to, the type the reference lists for it, and on `*` for a source with none. The Describe actions are authorized on `*`, as the reference lists no resource for them. Not modelled: delivery destination policies (`PutDeliveryDestinationPolicy` and its siblings), and record field defaults for sources other than an EventBridge event bus. ### Subscription filters {#subscription-filters} Subscription filters deliver newly ingested log events to a downstream destination. Floci delivers matching events to Lambda functions, Kinesis data streams, and Firehose delivery streams. Delivery happens synchronously on the calling thread when `PutLogEvents` persists events. A destination error, missing destination stream/function, or unresolvable destination ARN is logged and does not fail the log ingestion request. The delivered payload is a gzip-compressed JSON object containing `messageType` (`DATA_MESSAGE`), `owner` (the account ID), `logGroup`, `logStream`, `subscriptionFilters` (the matched filter names), and `logEvents` (an array of `{id, timestamp, message}`). Lambda receives the payload base64-encoded under `awslogs.data`. Kinesis and Firehose receive the gzip-compressed JSON bytes directly as record data. For Kinesis destinations, `distribution` controls the partition key: `ByLogStream` uses the log stream name, while `Random` assigns a randomized UUID partition key. Cross-account Logs destinations (`PutDestination`), IAM role permission checks, and the `CONTROL_MESSAGE` ping on filter creation are deferred. ### Metric filters {#metric-filters} A metric filter turns newly ingested log events into CloudWatch metric samples. Each matching event contributes the literal `metricValue`, or its referenced field (`$.latency` in JSON, `$size` in space-delimited logs), at the **event timestamp**, not ingestion or filter-creation time. Events ingested before the filter existed are not replayed. Backdated and future event timestamps remain backdated and future metric timestamps. A configured `defaultValue` contributes **once per nonmatching event**, including alongside matches in the same batch or minute. A matching event with a missing or JSON-null metric-value field also uses the default; a present nonnumeric value is skipped, not replaced by the default. Without a default, those nonmatches and missing/null values produce no sample. No events means no samples. Healthy publication is immediate and needs no subsequent ingestion, reads, or timer. For example, pattern `ERROR`, value 3 and default 7 produce Sum 13 / SampleCount 3 for `ERROR, INFO, ERROR`, and three quiet nonmatches produce Sum 21 / SampleCount 3. A late match appends its value without retracting earlier defaults. CloudWatch aggregates these contributions by period; Floci has no minute-default accumulator or deduplication history. Ordinary transformation dimensions are all-or-none: a complete configured set is emitted, while a missing member produces a dimensionless sample, not a partial set. Requested system dimensions (`@aws.account`, `@aws.region`) are populated on matches using the resolved receiving account and region, including regular noncentralized Logs ingestion. **Pattern-nonmatch defaults are dimensionless**, even when system dimensions are requested. These scenarios are supported by the recorded [live AWS observations](cloudwatch-metric-filters-verification.md). **Inferred emulator policy, not a live AWS claim:** matching missing/null metric-value fallbacks retain requested system dimensions. Likewise, an incomplete ordinary dimension set is discarded as a unit while requested system dimensions are retained. Null ordinary dimension values are treated as missing; empty strings retain the existing scalar-extraction behavior. These combinations were not measured by the recorded probes. Floci does not infer centralized source provenance. **Publication runs off the request thread:** `PutLogEvents` evaluates the group's filters as they are at that moment, builds one immutable sample per contributing event (canonical account, region, group, filter, transformation snapshot, event timestamp and a stable internal publication ID) and hands them to a process-wide queue. One managed worker writes them to the Metrics store, so ingestion latency does not depend on the Metrics sink and a `PutMetricFilter` or a reset waits for at most one sample write. The queue holds **100,000 samples**; a batch that does not fit is written on the request thread under the filter-store monitor instead of being dropped, so accepted samples are never lost to the bound and only an overfull queue makes the request wait on the sink. A read issued immediately after `PutLogEvents` may run before the worker has written the sample, as on AWS; SDK tests should poll. Shutdown drains the queue before storage shuts down. **Runtime publication failures:** accepted Logs ingestion remains successful if the Metrics sink reports a failure. Each failed sample keeps its snapshot and publication ID, and retries replace that same metric-store key, making partial or ambiguous writes safe without deduplicating distinct identical log events. The existing AWS `PutMetricData` APIs continue appending samples as before. The same worker retries failed publications at one-second intervals while both Logs and Metrics services are enabled; idle ticks never create defaults. The retry map holds at most **10,000 samples**, not 10,000 batches. This fixed conservative limit bounds outage memory without introducing a configuration surface. When full, new failed samples are dropped with an **ERROR** containing account, region, group, filter and dropped count; already queued samples and their IDs are preserved. Successful retries and cancellations release capacity. Each filter-owned outage logs one detailed stack, followed by a stack-free aggregate warning every 60 failed retry ticks. Recovery, cancellation and reset release that suppression. This is bounded best effort, not lossless delivery through an indefinite outage. Pending work is in memory only; crash-durable pending publication is not implemented. Storage failures that a backend only logs rather than throws are not observable to this retry path; configured storage durability semantics are unchanged. A filter update or deletion affects new ingestion only: samples already accepted for a batch still publish under the definition that was current at ingestion, as on AWS, and deleting a filter or group cancels only its own account/region-scoped failed retries without retracting stored metrics. Reset pauses publication, waits for the active sample write, discards queued and failed samples, wipes storage and resumes the same live service. The canonical filter-store monitor serializes each sample write with update/delete; reset hooks release it before the storage-factory wipe to avoid lock inversion. Shutdown writes the queued samples, abandons failed retries and stops the worker (up to five seconds to await executor termination). Storage backends expose synchronous operations without a cancellation deadline; a stuck backend can delay that drain. Runtime cancellation is not a crash-recovery guarantee. Samples are readable with `GetMetricStatistics` and `GetMetricData`, and alarms evaluate normally. The filter pattern syntax follows the AWS reference: - Terms: `ERROR ARGUMENTS` (all present), `?ERROR ?ARGUMENTS` (any present), `ERROR -ARGUMENTS` or `ERROR - ARGUMENTS` (exclusion), `"exact phrase"`. Terms are case-sensitive substrings of the message. - Regular expressions between percent signs, `%^[hc]at%`, with the operators and escapes AWS allows. Parentheses and characters outside ASCII are rejected, as on AWS. - JSON patterns: `{ $.eventType = "UpdateTrail" && $.code >= 400 }`, with `=`, `!=`, `<`, `<=`, `>`, `>=`, `IS NULL`, `IS TRUE`, `IS FALSE`, `NOT EXISTS`, `&&`, `||`, parentheses, array indexes, `[*]` and `.*` wildcards, and `$.['a.b']` for a property with a dot in its name. AWS's wildcard quotas apply: one per property selector and three per pattern. - Space-delimited patterns: `[ip, ..., status_code = 4*, bytes]`, with named fields, `...` for any number of fields, conditions on any field, `w1`/`w2` indicators, and `%regex%` values. Text between double quotes or square brackets is one field. `PutMetricFilter` applies the rules AWS applies: the log group must exist, the pattern must parse, at most two regular expressions per pattern, exactly one transformation whose `metricValue` is a number or a single-valued field reference, at most three dimensions in total, and 100 metric filters per log group. Scalar JSON metric-value and dimension references need not be mentioned in the filter pattern. Wildcard metric-value references such as `$.values[*]` are rejected; wildcards remain available in the filter pattern itself. Ordinary dimensions are available only for JSON or space-delimited patterns and cannot be combined with a `defaultValue`; system-only dimensions can. The shared group regex quota counts up to five **regex-bearing filters** across metric and subscription filters, independently of the two expressions allowed per pattern. This shared pool is documentation-backed, not a new live mixed-writer claim. `TestMetricFilter` reports one-based event numbers. JSON matches have empty public `extractedValues`; space-delimited matches expose named fields as `$name` and positional fields as `$1`, `$2` and so on. `fieldSelectionCriteria` selects which batches a filter processes from the system fields `@aws.account` and `@aws.region`, with `=`, `!=`, `IN`, `NOT IN` and the `AND` and `OR` the API documents, as in `@aws.account IN ["111111111111"]`. Both fields describe the ingested batch rather than the individual event, so one evaluation decides the batch. A criterion that does not parse is rejected when the filter is stored. `emitSystemFieldDimensions` adds `@aws.account` and `@aws.region` on matching contributions as described above. They count toward the same combined limit of three dimensions. `applyOnTransformedLogs` is stored and returned unchanged. Request acceptance was verified on AWS, including `true` on the tested group without a group-level transformer. Floci does not execute group-level or account-level log transformations, including stored `TRANSFORMER_POLICY` configuration. Accepting the flag therefore does not establish transformed-log processing or full compatibility with an AWS group that has an active transformer. See [Metric-filter contract verification](cloudwatch-metric-filters-verification.md) for the scenarios tagged **Verified on Live AWS**, the recorded fixtures and their evidence boundaries. ### Logs Insights {#logs-insights} `StartQuery` accepts log group names and canonical log group ARNs in `logGroupIdentifiers`. Floci also accepts the `:*` suffix and the bare trailing `:` produced when Grafana removes the `*` from `DescribeLogGroups.arn`. Equivalent identifiers scan the group only once. The bare-colon tolerance applies only to `logGroupIdentifiers`, requires a complete Logs ARN, and does not rewrite values supplied through `logGroupName` or `logGroupNames`. The bare-colon spelling is a client-compatibility tolerance: the [AWS reference](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html#CWL-StartQuery-request-logGroupIdentifiers) documents the canonical ARN, not that spelling. This tolerance does not change other APIs' ARN handling. `StartQuery` / `GetQueryResults` / `StopQuery` run a **subset** of the Logs Insights query language. As on AWS, `StartQuery` rejects a `queryString` longer than 10,000 characters with `InvalidParameterException`. Supported commands: | Command | Notes | |---|---| | `fields a, b, ...` | Projection. Defaults to `@timestamp, @message`. `display` is an alias | | `filter = 'v'` | Equality. `!=` and `==` are also accepted; `where` is an alias. An unquoted value must be a number and compares by value, so `n = 2` matches `2` and `2.0`. Comparisons can be joined with `or` (any case) and grouped with parentheses, for example `filter (type = 'A' or type = 'B')` | | `filter ispresent(field)` | Keeps events whose field exists and is not JSON `null` | | `filter field like /regex/` | Matches with a regular expression; `like 'text'` matches a substring, and `not like` negates either form | | `stats ... [by field, bin(1h)]` | Supports `count(*)`, `count(field)`, `count_distinct(field)`, and `latest(field)`, with optional aliases and grouping fields or time bins. Place `stats` after any filters and before `sort` or `limit` | | `sort [asc\|desc]` | `order` is an alias | | `dedup ` | Keeps the first row per unique tuple, applied after sorting | | `limit N` | The effective cap is the smallest of this value, the `StartQuery` `limit` parameter, and `FLOCI_SERVICES_CLOUDWATCHLOGS_MAX_EVENTS_PER_QUERY` | Fields may be `@timestamp`, `@message`, `@ingestionTime`, `@ptr`, or a dotted path into a JSON log message (for example `level` or `params.job_id`). A `@ptr` column is included in each nonaggregated result row, appended unless `fields` already names it. A `stats` result contains only its aggregate and grouping columns. For `stats` queries, `statistics.recordsMatched` counts matching log events, not aggregate result rows. For nonaggregated queries, it counts rows returned after `dedup` and `limit`. A command or filter operator outside this subset fails the query instead of being dropped: `StartQuery` still returns a query id, and `GetQueryResults` reports `status: Failed` with no rows. The reason is not part of the response (the AWS `GetQueryResults` shape has no such field); it is written to the server log as `Logs Insights query will fail: ...`. A few inputs still degrade silently, so it is worth knowing how each case behaves: | Input | Result | |---|---| | An unsupported command (`parse`, ...) | The query fails. Logged as `Unsupported command: parse` | | A `filter` whose operator is not supported, for example `<`, `<=`, `>`, `>=` or `=~ /ERROR/` | The query fails. Logged as `Unsupported filter expression: ...` | | A `filter` using `and`, a standalone `not` or `\|\|`, or with text after the value, as in `filter level = 'ERROR' x` | The query fails. AWS evaluates `and` and `not`, ignores the trailing text, and rejects an unparenthesized `\|\|` at `StartQuery` with `MalformedQueryException` (use `or`) | | A blank query, or an empty stage as in a trailing `\|` | The query fails. AWS rejects it at `StartQuery` | | A quoted filter value with a backslash escape, a backtick-quoted field name, an expression such as `1+1` in place of the field, or an unquoted value that is not a number, such as `level = ERROR` or `n = 1+1` | The query fails. Backslash escapes within `like /regex/` are supported | | A projected field that does not exist | Rendered as an empty string. No warning | | A `sort` direction other than `asc` / `desc` | Treated as ascending. No warning | For CloudWatch filter pattern syntax (`?ERROR ?WARN`, `{ $.level = "ERROR" }`, and so on), use `FilterLogEvents`. ### Reading events past the limit `FilterLogEvents` and `GetLogEvents` both page, and they signal the end of the results differently because the AWS APIs do. `FilterLogEvents` pages forward only. Its `nextToken` is an `f/` offset into the matched set, so the offset counts matches, not stored events: a request narrowed by `--filter-pattern`, `--start-time` or `--log-stream-names` pages through only what it matched. A missing token starts from the oldest match, and **a response with no `nextToken` means pagination is finished**, so the final page omits it. An unrecognized, non-numeric or negative token returns `InvalidParameterException` (400). `startFromHead` is not supported, so results always run oldest first. `GetLogEvents` pages in both directions with `f/` and `b/`, and always returns `nextForwardToken` and `nextBackwardToken`. It signals the end by returning the same token it was given rather than by omitting it, which is what its SDK paginators expect. ### Configuration | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_CLOUDWATCHLOGS_ENABLED` | `true` | Enable or disable the CloudWatch Logs service | | `FLOCI_SERVICES_CLOUDWATCHLOGS_MAX_EVENTS_PER_QUERY` | `10000` | Maximum events returned per `FilterLogEvents` / `GetLogEvents` call, and the upper bound for a Logs Insights `limit` | | `FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS` | `0` | Artificial Logs Insights query delay. With `0` a query completes immediately. A positive value emulates the real asynchronous lifecycle (`Running` → `Complete` after the delay), which also makes `StopQuery` on a still-running query return `success=true` | ### Storage Log groups, streams, filters and resource policies follow the configured storage mode as every other service does. The event store is the one CloudWatch Logs store under steady append load, so under `persistent` mode it is journaled instead of rewritten on every `PutLogEvents` call: a batch is appended to `cwlogs-events.wal`, and `cwlogs-events.json` is rewritten from memory on the `FLOCI_STORAGE_WAL_COMPACTION_INTERVAL_MS` cadence and at shutdown. The store keeps at most 20,000 events per account (`FLOCI_SERVICES_CLOUDWATCHLOGS_MAX_STORED_EVENTS`), which bounds both the memory footprint and the size of each snapshot. `hybrid` remains the alternative when a bounded delay for every CloudWatch Logs store is acceptable. See [Storage Modes](../configuration/storage.md#journaled-stores-under-persistent-mode). ### Examples ```bash export AWS_ENDPOINT_URL=http://localhost:4566 # Create a log group and stream aws logs create-log-group --log-group-name /app/backend --endpoint-url $AWS_ENDPOINT_URL aws logs create-log-stream \ --log-group-name /app/backend \ --log-stream-name 2025/01/app-1 \ --endpoint-url $AWS_ENDPOINT_URL # Write log events TIMESTAMP=$(date +%s%3N) # milliseconds aws logs put-log-events \ --log-group-name /app/backend \ --log-stream-name 2025/01/app-1 \ --log-events "[{\"timestamp\":$TIMESTAMP,\"message\":\"Service started\"}]" \ --endpoint-url $AWS_ENDPOINT_URL # Read log events aws logs get-log-events \ --log-group-name /app/backend \ --log-stream-name 2025/01/app-1 \ --endpoint-url $AWS_ENDPOINT_URL # Search logs aws logs filter-log-events \ --log-group-name /app/backend \ --filter-pattern "ERROR" \ --endpoint-url $AWS_ENDPOINT_URL # Run a Logs Insights query QUERY_ID=$(aws logs start-query \ --log-group-name /app/backend \ --start-time $(($(date +%s) - 3600)) \ --end-time $(date +%s) \ --query-string 'fields @timestamp, @message | sort @timestamp desc | limit 20' \ --query queryId --output text \ --endpoint-url $AWS_ENDPOINT_URL) aws logs get-query-results \ --query-id "$QUERY_ID" \ --endpoint-url $AWS_ENDPOINT_URL # Set retention aws logs put-retention-policy \ --log-group-name /app/backend \ --retention-in-days 30 \ --endpoint-url $AWS_ENDPOINT_URL ``` --- ## CloudWatch Metrics {#metrics} **Protocol:** Query (XML), JSON 1.0, OTLP/HTTP, and the Prometheus HTTP API ([PromQL](#promql)). `GetMetricStatistics` and `GetMetricData` exclude samples exactly at `EndTime`, so adjacent query windows do not count their shared boundary twice. A whole-second sample before a fractional-second `EndTime` remains included. The OTLP HTTP metrics endpoint accepts `POST /v1/metrics` with `application/json` or `application/x-protobuf`, optionally gzip-compressed. Requests are stored separately from classic CloudWatch metrics, retaining their OTLP resource, scope and metric data. The uncompressed request limit is 5 MiB and a request may contain at most 1,000 data points. Floci checks each datapoint's timestamp, the limit of 150 resource, scope and datapoint attributes combined, and the 40,000-byte metadata limit, which counts the resource and scope schema URLs as well, since PromQL reads them as labels of the series. Attribute strings are limited to 1,024 UTF-16 code units. Storage follows the `cloudwatchmetrics` storage configuration. The ingested metrics can be discovered through [PromQL](#promql), and the endpoint does not yet implement every CloudWatch OTLP validation rule. Invalid requests return OTLP `google.rpc.Status` bodies. When only part of a request is invalid, Floci returns an OTLP partial-success response and stores only the accepted datapoints. Empty or untyped metrics produce a partial-success message without increasing the rejected datapoint count. Stored batches expire 14 days after ingestion and are removed on a later ingestion in the same account and region. Cleanup runs at most once per minute for each account and region. With IAM enforcement enabled, requests require AWS credentials and the `cloudwatch:PutMetricData` permission. Bearer-token authentication for this endpoint is not implemented. CloudWatch Query operations accept form-encoded POST requests and root GET requests with URL query parameters. GET uses the existing handlers, signature validation and IAM policy checks. A `monitoring` credential in the Authorization header or presigned URL selects CloudWatch, including requests with browser Accept headers or unrelated target headers. Unsigned GET requests select it only for unambiguous supported actions; ordinary S3, SNS and browser requests retain their existing routing. Only a Query protocol claim can dispatch a CloudWatch GET; an unclaimed request cannot perform a CloudWatch operation. Header-signed and presigned requests use the account and region in their credential scope. `Action` takes precedence over `Operation`. Use `Version=2010-08-01` for current GET operations. Omitting the version selects the legacy `2009-05-15` API, which supports only `ListMetrics` and `GetMetricStatistics`. An invalid version or action returns HTTP 404 `InvalidAction`; an absent action returns HTTP 404 `UnknownOperationException`. IAM policies use the `cloudwatch` action prefix. With IAM enforcement on, each action is checked on the resources the AWS Service Authorization Reference lists for it, read from the request: an alarm by its `AlarmName` or each of its `AlarmNames`, as `arn:aws:cloudwatch:::alarm:`; a dashboard by its `DashboardName` or each of its `DashboardNames`, as `arn:aws:cloudwatch:::dashboard/`, with no Region; a metric stream by its `Name` or each of its `Names`, as `arn:aws:cloudwatch:::metric-stream/`; and a tag call on its `ResourceARN`. `PutMetricData`, `GetMetricData`, `GetMetricStatistics`, `ListMetrics`, `ListDashboards` and `ListMetricStreams` name no resource and are checked on `*`, as is a `DescribeAlarms` naming no alarm. JSON `PutMetricData` accepts a gzip-compressed body (`Content-Encoding: gzip`), which the AWS CLI, boto3 and the other SDKs that call CloudWatch over JSON send by default for any body of 10 KiB or more. With signature validation and IAM enforcement on, the signature is checked over the compressed bytes as sent and IAM decides the request before the body is decompressed. The decompressed body is limited to 5 MiB: a larger one returns HTTP 413 `RequestEntityTooLargeException`, a body that cannot be decompressed returns HTTP 400 `InvalidRequestException`, and an empty body reads as no input. Other JSON operations do not decompress their body. JSON and Query metric publication require finite numeric values in the inclusive range -2^360 through 2^360. They reject incomplete `StatisticValues` sets and datums combining `Value` with `StatisticValues` before storing any part of the batch. Missing statistics return `MissingParameter`; invalid values and non-object statistics return `InvalidParameterValue`; combining scalar and statistics returns `InvalidParameterCombination`. JSON bodies use the corresponding SDK exception shape names. `Values` accepts 1 to 150 numeric samples with optional matching, nonnegative `Counts`; omitted counts default to one. The public JSON and Query APIs normalize these weighted samples without expanding their counts. A `StatisticValues` set sent with `Values` summarizes the same distribution and is not counted again. Combining `Value` and `Values` is rejected. The console's supported numeric values use the same bounds. **Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST. JSON 1.0 requests name their operation in `X-Amz-Target` with the `GraniteServiceVersion20100801.` prefix the AWS SDKs send, or with `CloudWatchVersion20130116.`, the prefix of the CloudWatch console's API. Both get the same signature validation and IAM checks. The console prefix serves five operations on the same metrics and alarms, with these request members: `PutMetricData` (`Namespace`, `MetricData`), `ListMetrics` (`Namespace`, `MetricName`, `Dimensions`, `NextToken`), `DescribeAlarms` (`AlarmNames`, `AlarmNamePrefix`, `MaxRecords`, `NextToken`), `GetMetricStatistics` (`Namespace`, `MetricName`, `Dimensions`, `StartTime`, `EndTime`, `Period`, `Statistics`, `Unit`) and `DeleteAlarms` (`AlarmNames`). Every result comes back at once, so `MaxRecords` and `NextToken` change nothing. Console metric publication accepts a nonempty array of metric objects with either a finite numeric `Value` or a complete numeric `StatisticValues` object (`SampleCount`, `Sum`, `Minimum`, `Maximum`, with positive sample count), with string dimension names and values. Timestamps may be finite numeric epochs or valid ISO-8601/epoch strings. It rejects malformed batches, conflicting scalar/statistic-set readings, and unsupported datum fields such as `Values`, `Counts` and `StorageResolution` before storing any metrics. This supported subset is not complete console API parity. It returns HTTP 400 `UnsupportedOperation` for every other operation, such as the console's `GetMetricData` with `Defaults` and `Metrics`; for a request that sets any other member, such as `StateValue`, `ExtendedStatistics` or the console's `CountOnlyRequest`, to a value other than `false` or `null`; and for a `DescribeAlarms` answer that would list an alarm defined with `Metrics`, whose items the console's API shapes differently. Such an alarm makes every listing that includes it fail, so filter by `AlarmNames` or `AlarmNamePrefix` to list the others. The console prefix is JSON only: a CBOR request naming it returns HTTP 404 `UnknownOperationException`, and a Smithy RPC v2 request HTTP 404. Only the bare prefix over `application/x-amz-json-1.0` is accepted; the fully qualified `com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.` form over `application/json` returns HTTP 404. ### Supported Actions | Action | Description | |---|---| | `PutMetricData` | Publish custom metrics | | `ListMetrics` | List available metrics | | `GetMetricStatistics` | Get metric statistics (Average, Sum, etc.) | | `GetMetricData` | Query metrics with math expressions | | `PutMetricAlarm` | Create a metric alarm | | `PutCompositeAlarm` | Create or update a composite alarm rule | | `DescribeAlarms` | List alarms | | `DeleteAlarms` | Delete alarms | | `DisableAlarmActions` | Disable actions for named metric and composite alarms | | `EnableAlarmActions` | Re-enable actions for named metric and composite alarms | | `SetAlarmState` | Manually set alarm state | | `DescribeAlarmHistory` | List alarm state transitions and configuration changes (see [Alarm history](#alarm-history)) | | `PutMetricStream` | Create or update a metric stream definition | | `GetMetricStream` | Read a metric stream definition | | `ListMetricStreams` | List metric streams | | `DeleteMetricStream` | Delete a metric stream | | `StartMetricStreams` | Move metric streams to `running` | | `StopMetricStreams` | Move metric streams to `stopped` | | `PutDashboard` | Create a dashboard, or replace its body when the name is taken (tags apply on create only) | | `GetDashboard` | Read a dashboard body and ARN | | `ListDashboards` | List dashboards, optionally by name prefix | | `DeleteDashboards` | Delete dashboards by name | | `TagResource` | Tag an alarm or dashboard by ARN | | `UntagResource` | Remove tags from an alarm or dashboard | | `ListTagsForResource` | List the tags of an alarm or dashboard | Metric streams are stored as definitions with their `running` or `stopped` state. Floci never delivers metrics to the Firehose delivery stream a metric stream names. SQS publishes its queue metrics under `AWS/SQS` once a minute; see [SQS CloudWatch Metrics](sqs.md#cloudwatch-metrics). Composite alarms support boolean rules over alarm states. Request `AlarmTypes` containing `CompositeAlarm` when describing them; the default describes metric alarms. Composite action lists are stored but not executed. Action suppression is not implemented and is rejected with `ValidationError`. ### Metric storage {#metric-storage} Every datapoint is one entry in the metric store, which is held in memory and written out as a whole: about 500 bytes of JSON each in `cwmetrics.json`. Services that publish their own metrics fill it without a `PutMetricData` call: an active SQS queue adds 8 to 11 datapoints a minute. Floci therefore keeps at most 100,000 datapoints per account in each namespace it publishes itself, `AWS/SQS` and `AWS/Redshift` (`FLOCI_SERVICES_CLOUDWATCHMETRICS_MAX_STORED_DATAPOINTS`). Once a minute, an account holding more than that in one of those namespaces loses its oldest datapoints there, by datapoint timestamp and whichever metrics they belong to, until nine tenths of the ceiling are left. A store loaded from disk above the ceiling is cut back the same way a minute after startup. With the default, 50 active queues keep about four hours of history; raise the ceiling to keep more, up to the 15 days those datapoints are kept for, or set it to `0` to keep them all. Datapoints in any other namespace are never dropped for the ceiling, so what a client writes with `PutMetricData` under its own namespace stays. ### PromQL {#promql} CloudWatch serves PromQL through Prometheus-compatible HTTP endpoints on the monitoring host, over the metrics the OTLP endpoint ingested. Floci serves instant and range queries and the two discovery operations. | Operation | Path | Methods | IAM action | |---|---|---|---| | `QueryMetrics` | `/api/v1/query` | GET, POST | `cloudwatch:GetMetricData` and `cloudwatch:ListMetrics` | | `QueryMetrics` | `/api/v1/query_range` | GET, POST | `cloudwatch:GetMetricData` and `cloudwatch:ListMetrics` | | `GetSeries` | `/api/v1/series` | GET, POST | `cloudwatch:ListMetrics` | | `GetLabels` | `/api/v1/labels` | GET, POST | `cloudwatch:ListMetrics` | | `GetLabels` | `/api/v1/label//values` | GET | `cloudwatch:ListMetrics` | Requests are signed with Signature Version 4 under the `monitoring` service name and read the metrics of the account and Region in their credential scope. With IAM enforcement on, an unsigned request returns HTTP 403 `MissingAuthenticationTokenException`, as on the OTLP endpoint. The parameters (`query`, `time`, `match[]`, `start`, `end`, `step` and `limit`) go in the URL query string of a GET or as form fields in the body of a POST; where a POST gives one in both, its body's comes first, as Prometheus reads them. As Go's form parser, which Prometheus reads them with, a POST body is read only with the `application/x-www-form-urlencoded` content type, and one longer than 10 MiB returns HTTP 400 `bad_data` (`error parsing form values: http: POST too large`). A time is a Unix timestamp in seconds, which may have a fraction, or an RFC 3339 timestamp. `GetSeries` needs `match[]`, `start` and `end`, and each of its selectors an exact match (`=`) on the metric name. `GetLabels` takes all four as optional, and without `start` and `end` reads every stored batch. Every answer uses the Prometheus JSON envelope, `{"status":"success","data":...}`. `QueryMetrics` evaluates its `query` at `time`, the current time when the request gives none, and answers its `resultType` (`vector`, `scalar`, `string`, or `matrix` for a range selector or subquery) and `result`, each sample's time in seconds with three decimals as the guide's sample response writes it (`[1780000000.000, "42"]`), and its value as Prometheus writes one, with an exponent below 1e-6 and from 1e21 on (`1e-07`). Each series selector of the query has to match the metric name exactly ("Selecting series only by labels, without a metric name, is not supported"). Over a range, `QueryMetrics` evaluates its `query` at each `step` from `start` to `end`, both included, and answers a `matrix`: each series' values at the steps it has one, a scalar's as a series with no labels, the series in order of their labels as Prometheus sorts them, and `@ start()` and `@ end()` reading at `start` and `end`. All three are required. A `step` is seconds, which may have a fraction, or a duration such as `1m30s`, and the query a scalar or an instant vector. Prometheus's API checks come first, with its messages and HTTP 400 `bad_data`: a missing or unreadable time (`invalid parameter "start": cannot parse "" to a valid timestamp`), an `end` before `start`, a step it cannot read or of no time, and more than 11,000 points a series (`exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)`); then the guide's 30-day range, as for discovery. Evaluation follows Prometheus 3.0 over float samples: a selector takes each series' latest sample in the 5 minutes up to the time it reads, a range selector or subquery the samples in its range, left-open, and a subquery without a step steps every minute. The operators (arithmetic, comparison with or without `bool`, `and`, `or`, `unless`, with `on`, `ignoring`, `group_left` and `group_right`), the aggregations (`sum`, `avg`, `min`, `max`, `count`, `group`, `stddev`, `stdvar`, `topk`, `bottomk`, `quantile`, `count_values`), the `offset` and `@` modifiers, and every function Prometheus 3.0 has that is neither experimental nor of native histograms are served, each dropping the metric name where Prometheus does, and so are the histogram functions `histogram_count`, `histogram_sum`, `histogram_avg`, `histogram_stddev`, `histogram_stdvar`, `histogram_quantile` and `histogram_fraction`. The experimental functions and aggregations Prometheus serves only behind `--enable-feature=promql-experimental-functions` are refused as unknown. `quantile`, `quantile_over_time` and `histogram_quantile` warn of a quantile outside 0 to 1 (`PromQL warning: quantile value should be between 0 and 1, got 2`), as Prometheus does. A series carries the labels the user guide's "PromQL querying" page gives an OTLP data point: `__name__` for the metric name; `@resource.` and `@resource.@schema_url`; `@instrumentation.@name`, `@instrumentation.@version`, `@instrumentation.@schema_url` and `@instrumentation.`; each data point attribute under its bare key; and `@aws.account` and `@aws.region`, the account and Region it was ingested in. A selector can also name a data point attribute as `@datapoint.` and the metric name as `@datapoint.@name`. A label with an empty value is no label. A data point attribute whose key starts with `@` or `__` is not kept, as it would read as a scoped or reserved label. An attribute value that is not a string is rendered as the OpenTelemetry Collector renders one: `true` or `false`, a decimal integer, a double as JavaScript prints a number, bytes in base64, and an array or a key-value list as JSON. Gauge and sum data points become float samples, and exponential and explicit-bucket histogram data points histogram samples. A summary's data points carry no sample, as the guide lists gauge, sum, histogram and exponential histogram as the OpenTelemetry metric types it stores, and neither does a data point flagged as having no recorded value. An exponential histogram becomes a native histogram as Prometheus's OTLP translator converts one: a scale above 8 is lowered to 8, merging the buckets it joins, a scale below -4 carries no sample, as does a data point whose buckets lie past the bucket of infinite observations, which no double can bound, and the zero bucket's threshold is Prometheus's `1e-128`, a bucket wholly within it counted in the zero bucket. An explicit-bucket histogram becomes an exponential one, as the guide's "How CloudWatch stores histogram metrics" says CloudWatch converts one at ingestion: its count and sum are kept exactly, and each bucket's count goes to the exponential buckets that cover its range, weighted by how its density compares with its neighbors' rather than spread evenly. The guide gives no more of the algorithm, so Floci's is its own. Within a delta data point's bucket the density runs linearly from edge to edge, each edge's density the mean of the two buckets it divides (the bucket's own at the histogram's ends), and the unbounded lowest and highest buckets reach the data point's `min` and `max` when it records them. Any other data point, a cumulative one among them, has its buckets spread evenly, as `histogram_quantile` assumes of a classic histogram's, and its `min` and `max` are not read: the guide's "Querying histogram metrics" reads a cumulative histogram's growth with `rate`, which takes a bucket that falls for a counter reset, and a bucket weighted by its neighbors, or reaching a maximum, gives up observations from part of its range as they grow. Without a `min`, the lowest bucket reaches down to zero when its bound is above zero, as `histogram_quantile` assumes of a classic histogram, and stays at its bound when that is not above zero; without a `max`, the highest bucket stays in the bucket just above its bound, where Prometheus places a quantile in it. A bucket that reaches zero becomes the zero bucket, its threshold the bucket's other bound (the nearer one for a bucket across zero), so a quantile in it is interpolated linearly from zero, as in a classic histogram's lowest bucket. The schema is the finest, at most 8, that holds the buckets in at most 160, an OpenTelemetry SDK's default size for an exponential histogram; the schema and the zero bucket depend on the bounds, and a delta data point's `min` and `max`, never on the counts. A data point whose bounds are not finite and strictly increasing, or whose bucket counts are neither one more than its bounds nor none, carries no sample. One without bounds keeps its count and sum only, unless it is a delta data point with a `min` and a `max`, whose one bucket runs between them. A histogram series is labelled `__type__="histogram"` and `__temporality__` `cumulative` or `delta`, the labels the guide's "Querying histogram metrics" reads; float series carry neither. `__type__` is dropped with the metric name, as Prometheus drops it. A histogram sample comes back under `histogram` (`value` for a float), and a range's under `histograms` beside its floats' `values`, as Prometheus writes them: `{"count": ..., "sum": ..., "buckets": [[rule, lower, upper, count], ...]}`, the buckets with a count lowest first. As Prometheus's documentation says, a function that does not mention native histograms ignores histogram samples: `count`, `group`, `count_values`, `count_over_time`, `present_over_time`, `last_over_time`, `timestamp`, `label_replace` and `label_join` take them, `histogram_count`, `histogram_sum` and `histogram_avg` read them, and `min`, `max`, `stddev`, `stdvar`, `quantile`, `topk` and `bottomk` skip them with Prometheus's informational annotation (`PromQL info: ignored histogram in min aggregation (1:5)`) in the response's `infos`, as do the float-only range functions for a range holding both kinds. Histograms are added and subtracted, multiplied by a float and divided by one, negated, and compared with `==` and `!=`, as Prometheus does it: two histograms are first brought to the coarser schema, merging the finer one's buckets, and to the larger zero threshold, the zero bucket taking the buckets it then covers. Any other pairing of a histogram with a float or a histogram keeps nothing, with `bool` too, and Prometheus's `incompatible sample types encountered for binary operator` info says so. `sum` and `avg` add histograms with Kahan compensation, `avg` falling back to a running mean when the sum overflows, and so do `sum_over_time` and `avg_over_time`; a group or a range of both floats and histograms has no result, with Prometheus's warning (`PromQL warning: encountered a mix of histograms and floats for aggregation`) in the response's `warnings`. `rate`, `increase` and `delta` over a histogram's range take its last histogram, at the coarsest schema of the range, less its first, extrapolated as a float's change is, the count standing in for the value; for `rate` and `increase` each histogram before a counter reset is added back, a reset being a fall in the count, the zero bucket or a bucket, or a finer schema, as Prometheus detects one; an OTLP data point's start time is not read, as Prometheus reads start times only behind its experimental `st-storage` feature. `irate` and `idelta` take the last two samples, `resets` and `changes` count over floats and histograms in time order, and a range of both kinds has no `rate` or `irate`, with Prometheus's `encountered a mix of histograms and floats` warning. A histogram keeps no counter reset hint, which the guide's "every histogram, including delta histograms" also says, so `rate` treats each as a counter, and `delta` and `idelta`, which expect gauge histograms, give Prometheus's `this native histogram metric is not a gauge` warning. `histogram_quantile` and `histogram_fraction` estimate from a native histogram's buckets as Prometheus does: the rank is found from the lowest bucket for a quantile below 0.5 and from the highest otherwise, and interpolated within its bucket exponentially, linearly in the zero bucket, which reaches only to zero when the histogram has buckets on one side only. `histogram_stddev` and `histogram_stdvar` take each bucket's observations at the geometric mean of its bounds. Float series with an `le` label are read as the buckets of a classic histogram, grouped by their other labels: sorted, buckets of the same bound added together, and counts that fall raised to the count before, with Prometheus's `input to histogram_quantile needed to be fixed for monotonicity` info, merged over the samples it was given for. A float series whose `le` is missing, or is no number or `NaN` as Go reads one, is left out with Prometheus's `bucket label "le" is missing or has a malformed value` warning, and a native and a classic histogram of the same labels both are, with its `vector contains a mix of classic and native histograms` warning. Histogram behavior follows Prometheus's latest release, 3.16, whose histogram behavior the guide describes, such as the `ignored histogram` annotation that 3.0 does not have. Selectors follow Prometheus 3: a metric name or label name may be quoted, which a name with a dot has to be (`{"http.server.active_requests", "@resource.service.name"="myservice"}`), and a matcher is `=`, `!=`, `=~` or `!~`. A regular expression is RE2's, as in Prometheus, and matches the whole value: a backreference or a lookaround returns HTTP 400 `bad_data`, and matching takes time linear in the value. Series, label names and label values come back sorted, as Prometheus sorts them. These limits from the user guide's "PromQL limits and restrictions" apply: - A query's result holds at most 500 series, or `limit` (1 to 500) of them; a longer one is truncated with the guide's warning, `result truncated to the maximum of 500 series; refine the query or use the limit parameter`, the number being the cap applied. - A discovery answer holds at most 10,000 series, label names or values, or `limit` (1 to 10,000) of them. A longer result is truncated and the envelope carries the warning `results truncated due to limit`, which Prometheus gives a result its limit truncated; the guide gives no wording for it. The status stays 200. - A matcher whose value or label name is longer than 5,000 bytes returns HTTP 400 `bad_data`, as does a `label_name` in the path of `/api/v1/label//values` that is. - A `start` and `end` more than 30 days apart return HTTP 422 `execution`. - A request that would scan more than 100,000 series, or 300,000,000 samples, in one 24-hour window returns HTTP 422 `execution`. A series or sample is scanned when the request's selectors select it within its time range, and the windows are UTC days. - A request still running after 20 seconds, the guide's execution timeout, returns HTTP 422 `execution`, whatever its selectors select. Beyond the guide's limits, a query holding more than 50,000,000 samples in memory, those it loads and those it computes for a range, returns HTTP 422 `execution` with Prometheus's message for its `--query.max-samples` default, as does one that would take what the requests running at once hold between them past a quarter of the JVM's heap. A query reads the store once for all its selectors, keeping a sample only when a selector selecting its series reads at its time, so `m + m offset 1d` keeps two five-minute windows, not the day between them. What a request holds is counted as: - the text of its parameters, about 24 bytes a character for what parsing it builds, while it runs; - a sample it loads as its 16 bytes, twice that again while it is gathered, and a series as its labels and about 256 bytes more; the read's own record of the series and 24-hour windows it has seen, about 96 bytes for each series and 256 for each window, for discovery too; - a vector it computes as about 40 bytes a sample, and each label set it holds once, however many series and vectors carry it on, as a selector, `sort` or a filter does, with the labels `label_replace` and `label_join` write; these count until the query is evaluated, or until the end of the subquery step they are computed in, the subquery then counting the samples and label sets it keeps; - the signatures a vector matching or set operator keeps while it runs, and the copy of the values `quantile_over_time` sorts while it sorts it; - a stored histogram as about 32 bytes a bucket while it is converted, which happens only once a query keeps it, and its buckets as 8 bytes each after, each histogram counted once in a result however many samples share it; a histogram the engine builds as it is built, and the sum of histograms as its buckets and their compensation grow, every bucket between two histograms' included; the text `count_values` labels a histogram with, before it is written; and each informational annotation kept. A range's samples are given back once the function reading them has reduced them. Once a query is evaluated it gives back all it holds but its result, which counts until its response has been written, or the client has gone; a response not written within 20 seconds, the guide's execution timeout, is reset, so a client that stops reading cannot keep it counted. `label_replace` writes only to a name of letters, digits and underscores, not starting with a digit, and `label_join` reads and writes only names that are not empty, as Prometheus 3.0 checks them, refusing others with HTTP 422 `execution`. An expression nested more than 256 levels deep, counting operators chained left to right, returns HTTP 400 `bad_data`, as does a string literal longer than 5,000 bytes, the limit the guide gives a matcher's value. A regular expression Go's `regexp` would refuse as too large (over 128 MiB of compiled program) or nested more than 1,000 levels deep is refused before it is compiled, in a selector as `bad_data` and in `label_replace` as `execution`, a pattern being sized as Go's parser sizes it, an empty group or alternative included. As the regular expression library Floci uses builds about 110 bytes for each instruction Go would compile, and copies a Unicode class's ranges into each class naming it (a `\p` class counts as 128 instructions, a bracket class more as it grows), the regular expressions of one request, its selectors' and `label_replace`'s, may compile to 100,000 such instructions between them, and a query compiles each of its patterns once. An account runs at most 30 query requests (`/query`, `/query_range`) and 30 discovery requests at once, the guide's concurrency limits, a request holding its place while it is read, parsed and evaluated; one past that returns HTTP 429 with `errorType` `unavailable` and Floci's own message, as the guide gives none. The per-account TPS limits are not enforced, and neither are the samples processed per 24-hour window (3,000,000,000), which the execution timeout reaches first. Errors use the Prometheus error envelope, `{"status":"error","errorType":"bad_data","error":"..."}`. Where Prometheus has a message for a failure (`no match[] parameter provided`, `end timestamp must not be before start time`, a timestamp it `cannot parse`, a query's parse and type errors, a vector matching that finds duplicate series), Floci answers with it; the guide gives no messages, so the others are Floci's own. A query Prometheus cannot parse returns HTTP 400 `bad_data`, its message after `invalid parameter "query": ` as Prometheus's API gives it (`invalid parameter "query": 1:1: parse error: no expression found in input`), and one it cannot evaluate HTTP 422 `execution`. ### Metric alarm updates Updating a metric alarm preserves its current state, state reason, state timestamps and tags. Tags supplied to `PutMetricAlarm` apply only when creating an alarm; use `TagResource` and `UntagResource` to change existing tags. `SetAlarmState` requires `StateReason` and rejects missing or unknown state values before changing the alarm. `PutMetricAlarm` refuses an `EvaluationInterval` on an alarm configured with `MetricName` or `Metrics` with `InvalidParameterCombination`: the API reference allows it only with `EvaluationCriteria`, which Floci does not model and accepts without keeping the interval. Over Query and through CloudFormation an integer outside 10 to 3600, of any size, is a `ValidationError`; a value that is not an integer is an `InvalidParameterValue` over Query, a `SerializationException` over JSON and CBOR (as is a number beyond 32 bits) and a failed resource through CloudFormation. AWS documents none of these answers. An `AWS::CloudWatch::Alarm` fails the same way on create and on update, so a stack that sets the property cannot change that alarm until its template drops it. `StateTransitionedTimestamp` records when an alarm's `StateValue` last changed, while `StateUpdatedTimestamp` moves on every state update, including one that keeps the value. Alarms stored before Floci recorded it report their last state update. `SetAlarmState` enforces the modeled maximum lengths of 1023 characters for `StateReason` and 4000 characters for `StateReasonData` before changing alarm state. Length checks count Unicode code points and preserve empty and whitespace values. ### Composite alarm evaluation A composite alarm is evaluated when it is created, when `PutCompositeAlarm` updates it, and when one of its children changes state, up through nested composite alarms. `PutMetricAlarm` on an existing child, or a `SetAlarmState` to the state a child already has, is not a change of state, so a composite alarm set with `SetAlarmState` keeps that state until a child really changes. An update that leaves the state unchanged also keeps the state reason, reason data and timestamps. A composite alarm on a cycle of rules is not evaluated, not even by the update that closes the cycle, where CloudWatch evaluates that alarm and the ones after it. One above a cycle is still evaluated when one of its children changes state. A change of state records the `StateReason` CloudWatch writes: - ` was created and its alarm rule evaluates to OK` when the alarm is created, - ` was updated and its new alarm rule evaluates to ALARM` when an update changes it, - ` transitioned to ALARM at Monday 14 September, 2026 06:29:58 UTC` when a child does. `StateReasonData` lists under `triggeringAlarms` the children whose state agrees with the new one, the most recently changed first, each with its state and when it took it. After a child's change it lists only the children that changed state since the composite alarm last did. The list stops before the 4000 characters `StateReasonData` can hold, counted in Unicode code points like the length checks. Floci keeps state times to the second, so the timestamps end in `.000`. Every alarm a rule names must exist, or `PutCompositeAlarm` fails with `ValidationError` and `Could not save the composite alarm as alarms [] in the alarm rule do not exist`. `DeleteAlarms` deletes nothing when it names more than one composite alarm (`Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single request`) or an alarm that a composite alarm's rule names, even when it deletes that composite alarm too (`Cannot delete as there are composite alarm(s) depending on it.`), so delete composite alarms before their children. Names that match no alarm are ignored. ### SNS alarm actions State transitions publish to same-account standard SNS topics in `AlarmActions`, `OKActions`, or `InsufficientDataActions`, including transitions from `SetAlarmState`. Unchanged states and `ActionsEnabled=false` suppress notifications. `DisableAlarmActions` and `EnableAlarmActions` update this setting through the Query and current JSON APIs, preserving the alarm's state, actions, tags, and other configuration. They accept up to 100 names, ignore nonexistent alarms, and validate the whole request before updating any alarm. Enabling actions does not replay notifications for transitions that occurred while disabled. Query requests validate all supplied numeric member indexes, including names after a gap. The metric evaluator checks current stored action settings before dispatch; disabling does not cancel actions that have already passed that check. Scaling action retries remain independent. Failures are logged per target without blocking other targets. Notifications include a single-metric `Trigger`; durable retries, FIFO topics, and metric-math payloads are not covered. ### Metric-math alarm definitions `PutMetricAlarm` stores the `Metrics` query definitions and `DescribeAlarms` returns them over both JSON and Query protocols. Expressions, labels, `ReturnData`, account IDs, query periods, and nested metric statistics (including dimensions and units) survive storage reloads. Metric-math alarm responses omit the single-metric fields, including top-level `Period`. Updating an alarm replaces its metric definition, so changing between `Metrics` and a single metric does not retain the previous definition. This is management-plane support: the alarm evaluator currently evaluates only single-metric alarms, not metric-math expressions. `SetAlarmState` remains available for manual transitions. ### DescribeAlarms filters {#describealarms-filters} `DescribeAlarms` applies every filter a request gives: `AlarmNames` or `AlarmNamePrefix`, `AlarmTypes`, `StateValue` and `ActionPrefix`. `StateValue` and `ActionPrefix` narrow metric and composite alarms alike. The API reference calls `ActionPrefix` a prefix for any action, so an alarm matches when one of its `AlarmActions`, `OKActions` or `InsufficientDataActions` starts with it. `ChildrenOfAlarmName` lists the metric and composite alarms a composite alarm's rule names, by name or ARN, with only their name, ARN, `StateValue` and `StateUpdatedTimestamp`. `ParentsOfAlarmName` lists the composite alarms whose rules name an alarm, with only their name and ARN. Neither lists the alarm it names. Either one with any other member except `MaxRecords` and `NextToken` is refused with `ValidationError`, as is a `StateValue` outside `OK`, `ALARM` and `INSUFFICIENT_DATA`, an empty or over-long `ActionPrefix`, and an empty or over-long alarm name in either member. `MaxRecords` and `NextToken` are accepted, but every match comes back in one response. ### Alarm history {#alarm-history} `DescribeAlarmHistory` lists two kinds of items, newest first unless `ScanBy` is `TimestampAscending`: - `StateUpdate` for every real state transition, whether it comes from `SetAlarmState`, the alarm evaluator or a composite alarm's rule. Setting an alarm to the state it already has records nothing. `HistoryData` carries the old and new state with their reasons and reason data. - `ConfigurationUpdate` when `PutMetricAlarm` or `PutCompositeAlarm` creates or updates an alarm, when `EnableAlarmActions` or `DisableAlarmActions` changes its action setting, and when `DeleteAlarms` deletes one. An update lists the previous value of each changed field under `originalUpdatedFields`. History survives the deletion of its alarm and is kept for 30 days. Without `AlarmTypes` only metric alarm history is listed; request `CompositeAlarm` to include composite alarms. `Action`, `AlarmContributorStateUpdate` and `AlarmContributorAction` are accepted filters, but Floci never records those items, so they match nothing. `MaxRecords` defaults to 50, and a `NextToken` issued for the other `ScanBy` direction returns an empty page, as on AWS. The alarm snapshots in `ConfigurationUpdate` items use Floci's field names, such as `okActions` and `statistic`, where AWS uses its internal ones, such as `okactions` and `extendedStatistic`. ### Examples ```bash export AWS_ENDPOINT_URL=http://localhost:4566 # Publish a custom metric aws cloudwatch put-metric-data \ --namespace MyApp \ --metric-data '[{ "MetricName": "RequestCount", "Value": 42, "Unit": "Count", "Dimensions": [{"Name":"Service","Value":"api"}] }]' \ --endpoint-url $AWS_ENDPOINT_URL # List metrics aws cloudwatch list-metrics \ --namespace MyApp \ --endpoint-url $AWS_ENDPOINT_URL # Get statistics aws cloudwatch get-metric-statistics \ --namespace MyApp \ --metric-name RequestCount \ --dimensions Name=Service,Value=api \ --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ) \ --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \ --period 300 \ --statistics Sum \ --endpoint-url $AWS_ENDPOINT_URL # Create an alarm aws cloudwatch put-metric-alarm \ --alarm-name high-error-rate \ --metric-name ErrorCount \ --namespace MyApp \ --statistic Sum \ --period 60 \ --threshold 10 \ --comparison-operator GreaterThanThreshold \ --evaluation-periods 1 \ --endpoint-url $AWS_ENDPOINT_URL ```