Files
floci/docs/configuration/application-yml.md
T
Kenshin Okinaka fb26731131 feat(lambda): enforce reserved and per-region concurrency (#424)
* feat(lambda): enforce reserved concurrency at invocation time

Introduce LambdaConcurrencyLimiter using AtomicInteger + CAS. Acquire a
permit before invoke and release in finally for both sync and async
paths. DryRun skips enforcement. Functions without a reserved value are
not enforced in this step (account-pool enforcement will follow).

Reset inflight counters when a function is deleted to prevent leaks.

* test(lambda): use JUnit Assertions in LambdaConcurrencyLimiterTest

AssertJ is not on the unit-test classpath; switch to the Jupiter
assertions already used by sibling tests.

* feat(lambda): enforce account-wide concurrency pool and validate Put

Extend LambdaConcurrencyLimiter with an account-shared unreserved pool
sized as accountLimit - Σreserved. Functions without a reserved value
now share this pool; exhaustion returns TooManyRequestsException.

PutFunctionConcurrency rejects values that would leave less than
unreserved-concurrency-min (AWS default: 100) available, matching AWS's
LimitExceededException behavior.

Config: floci.services.lambda.account-concurrency-limit (default 1000)
and floci.services.lambda.unreserved-concurrency-min (default 100).
Docs and controller javadoc updated accordingly.

* feat(lambda): rehydrate reserved concurrency and handle throttle in pollers

On startup, LambdaService walks functionStore.listAll() and re-registers
reserved values with the limiter so validatePut and the unreserved pool
see the correct totals before the first Put of the session.

SQS/Kinesis/DynamoDB Streams pollers now catch TooManyRequestsException
explicitly. SQS lets messages return via visibility timeout; Kinesis and
DynamoDB Streams skip advancing the shard iterator, so records are
redelivered on the next poll.

* test(lambda): add SDK compatibility tests for concurrency enforcement

Verify end-to-end wire behavior: LimitExceededException on Put that
violates unreserved-min, TooManyRequestsException on Event invoke when
reserved=0, and DryRun bypassing the concurrency gate.

* fix(lambda): close concurrency races in limiter and rehydrate

- Recompute cap inside the unreserved CAS loop so concurrent setReserved
  does not leave permits granted above the live pool.
- Replace validatePut + setReserved with a single validateAndSetReserved
  guarded by a reservedLock; concurrent Puts for different functions
  can no longer each pass validation against stale totals.
- Rehydrate only $LATEST entries so published versions do not
  double-count into totalReserved().

* fix(lambda): address PR review feedback

- Partition limiter state by region. AWS Lambda concurrency is per
  account-per-region; functions in different regions no longer share
  the same reserved totals or unreserved pool.
- PutFunctionConcurrency and DeleteFunctionConcurrency now roll back
  the limiter update if functionStore.save() fails, so limiter and
  persisted state stay consistent.
- Replace the awkward (InvokeResult) null cast in the DynamoDB Streams
  poller with a plain forward declaration.

* refactor(lambda): rename account-concurrency-limit to region-concurrency-limit

The limit applies per-region (AWS Lambda's "account-level" quota is
actually per-account-per-region). Rename the config key, field, and
accessor to match what the value controls, and clarify the doc note.

No functional change.

* fix(lambda): O(1) region total and compare-and-rollback on save failure

- Maintain per-region AtomicInteger running total of reserved values,
  updated under reservedLock on every mutation. acquireUnreserved reads
  the cap in O(1) without iterating the map, eliminating the weakly-
  consistent partial-sum window that existed when reads happened off
  the lock while writes were serialized.
- Replace unconditional rollback with rollbackReservedIfExpected: the
  limiter only restores the previous value if the current entry still
  matches what the caller wrote, so a concurrent successful Put cannot
  be clobbered by an earlier request's rollback after its save fails.

* docs(lambda): scrub remaining account-wide wording and document drain semantics

Replace lingering "account-wide" / "account pool" phrasing with
per-region terminology in the controller javadoc and unit-test comment.
Two references remain by design: EmulatorConfig and the lambda service
doc quote AWS's own "account-level" label to explain the renamed key.

Also fold two follow-up review items into this change:
- Replace fully-qualified AwsException / InvokeResult references in the
  SQS, Kinesis, and DynamoDB Streams pollers with normal imports.
- Document that reducing or clearing a reserved value does not kill
  already-inflight invocations, mirroring AWS behavior and causing a
  brief drain window where total inflight may exceed the region limit.

* fix(lambda): serialize Put/Delete per function and preserve busy inflight

- Wrap PutFunctionConcurrency and DeleteFunctionConcurrency in a
  per-function lock so concurrent requests for the same ARN can't
  interleave the limiter update and the store save in a way that
  leaves them out of sync.
- Retain the inflight counter on reset when permits are still open,
  so an ARN recreated under load sees the remaining inflight rather
  than starting fresh and briefly allowing more than reserved capacity.
  Idle counters (value 0) are still dropped to prevent leaks.
- Tests now close acquired permits via try-with-resources and cover
  both the retain-while-busy and drop-when-idle reset behaviors.

* test(lambda): close all permits via try-with-resources

Close the acquire() result in regions_areIndependent so the test leaves
no inflight state behind and accurately asserts both the exhausted and
recovered cases.

* perf(lambda): avoid regex split in regionOf on the invoke hot path

regionOf() runs on every acquire/release. Replace String.split(":"),
which uses regex and allocates an array, with a single pass that finds
the fourth ':' segment and returns a substring — same semantics, no
allocation beyond the returned region string.

* fix(lambda): keep per-function lock map and tighten compat assertion

- deleteFunction no longer removes the per-function entry from
  concurrencyOpLocks. Removing it could race with a concurrent
  Put/Delete still synchronized on the old lock object, letting the
  next request create a fresh lock and run in parallel — defeating
  the very serialization the map provides. The map grows by one
  Object per deleted function, acceptable for a local emulator.
- LambdaConcurrencyTest now asserts the wire-level error identity
  (400 status + "LimitExceededException" errorCode) for the Put
  rejection. The Lambda SDK v2 model does not declare a typed
  LimitExceededException class, so wire-level assertions catch
  protocol-fidelity regressions more precisely than the previous
  generic LambdaException check.

* fix(lambda): retain inflight counter on reset and allow over-committed reductions

- reset() no longer drops idle inflight counters. The previous
  counter.get()==0 + remove pattern races with a concurrent
  acquireReserved that has already obtained the AtomicInteger
  reference and is about to increment it: a successful remove
  between those two moments would leave the next acquire to
  allocate a fresh counter and silently undercount inflight,
  permitting reserved over-subscription.
- validateAndSetReserved now allows any value <= the function's
  current reservation unconditionally. Reductions cannot worsen
  unreserved capacity, so blocking them in an already over-committed
  state (e.g. after lowering region-concurrency-limit at runtime)
  prevented operators from recovering. Increases still go through
  the unreserved-min check.

* fix(lambda): take per-function lock in deleteFunction

A concurrent deleteFunction + Put/DeleteFunctionConcurrency for the
same ARN could interleave the limiter reset and the store delete,
leaving the limiter holding (or clearing) state for a function the
store no longer knows about. Wrap the limiter+store mutations in the
same lockForConcurrencyOp(arn) used by the concurrency endpoints.

Tighten the surrounding comment so it describes the current code
rather than the lock-removal call that earlier revisions used to have.

* test(lambda): wire a real concurrency limiter into the test constructor

The package-private LambdaService constructor used by unit tests passed
null for concurrencyLimiter, so the null-guards in
putFunctionConcurrency / deleteFunctionConcurrency / deleteFunction made
those paths silently skip validation and limiter bookkeeping under tests.
That hid divergence from production behavior.

Construct a default LambdaConcurrencyLimiter (AWS defaults: 1000 / 100)
in the test ctor so the same enforcement runs in unit tests.

* test(lambda): cover concurrent PutFunctionConcurrency for the same ARN

Verify that the per-function lock in LambdaService serializes racing
Puts so the limiter and the functionStore always agree on whichever
write landed last. 50 iterations across two threads against the same
function exercise the lock discipline and assert store/limiter
consistency on every iteration.

* docs: document reserved concurrency config keys

- docs/services/lambda.md: drop redundant "(enforced at invocation)"
  from the PutFunctionConcurrency table entry (the admonition below
  already explains enforcement); add region-concurrency-limit and
  unreserved-concurrency-min to the Configuration YAML sample.
- docs/configuration/application-yml.md: mirror the two new keys in
  the top-level reference sample so every known lambda setting is
  discoverable in one place.

* refactor(lambda): address review feedback (A)

- LambdaServiceTest.concurrentPutFunctionConcurrency now asserts against
  limiter.totalReserved(region) instead of getFunctionConcurrency(), which
  read the same field as the value under test. The new assertion actually
  proves the limiter and the persisted store stayed in agreement.
- Expose a package-private concurrencyLimiter() accessor on LambdaService
  so tests can inspect limiter state without reflection.
- Drop unused Permit.NOOP: the reserved=null path now runs through
  acquireUnreserved and always returns a real decrement closure.
- Document the intentional unbounded growth of the inflight counter map
  (race avoidance on reset) and concurrencyOpLocks (race avoidance on
  deleteFunction). Both are acceptable for a local emulator workload.

* test(lambda): add rehydrate, multi-ARN race, and qualified-invoke coverage

- LambdaServiceTest.rehydrateConcurrency_restoresReservedFromStore
  prepopulates a LambdaFunctionStore with reserved values, builds a
  fresh LambdaService over it, and verifies totalReserved(region) goes
  from 0 to the expected sum after the @PostConstruct hook runs.
- LambdaServiceTest.multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention
  races two Puts on different ARNs that would together push the region
  below unreserved-min. reservedLock must let exactly one win; the
  other must fail with LimitExceededException and the limiter's total
  must reflect only the winning reservation.
- Compat LambdaConcurrencyTest.invoke_withVersionQualifier_stillHonorsReservedOnLatest
  publishes a version, sets reserved=0, and invokes with the qualifier
  set. Today Floci drops the qualifier and routes to $LATEST, so the
  reservation throttles the call. This test locks the behavior in: a
  future qualifier-routing change must either copy the reservation onto
  the snapshot or key the limiter off the base ARN to keep it green.

* refactor(lambda): idempotent permits, warn on malformed ARN, more tests

- Wrap acquire()/release() counter closures in an AtomicBoolean guard so
  a double-close of a Permit can never drive the inflight counter
  negative. Future callers that mix try-with-resources with explicit
  close, or that add retry logic around invoke, stay safe by default.
- regionOf() now warns once per unique malformed input instead of
  silently coalescing everything into "unknown". The first occurrence
  is logged so a bug that passes a bare function name into the limiter
  is debuggable without spamming the log.
- New LambdaServiceTest.putFunctionConcurrency_rollsBackLimiterIfSaveFails
  injects a failing LambdaFunctionStore and verifies the limiter total
  is restored when functionStore.save throws.
- New LambdaServiceTest.deleteFunction_preservesInflightPermitUntilItCloses
  holds a permit through a deleteFunction call and asserts the inflight
  counter stays live until the permit is closed.
- New LambdaConcurrencyLimiterTest.permit_closeIsIdempotent locks in the
  double-close guarantee.
2026-04-14 01:09:22 -05:00

9.1 KiB

application.yml Reference

All settings can be provided as YAML (mounted as a config file or in src/main/resources/application.yml) or overridden via environment variables (FLOCI_ prefix, dots/dashes replaced with underscores).

URL configuration

Floci generates absolute URLs for certain response fields (SQS queue URLs, SNS subscription endpoints, pre-signed S3 URLs). Two settings control the hostname embedded in those URLs:

Setting Env variable Default Description
floci.base-url FLOCI_BASE_URL http://localhost:4566 Full base URL used to build response URLs. Change the scheme, host, and port together.
floci.hostname FLOCI_HOSTNAME (none) Override only the hostname in base-url. Useful in Docker Compose where localhost is unreachable from other containers.

When floci.hostname is set it replaces just the host portion of base-url, leaving the scheme and port unchanged. Setting FLOCI_HOSTNAME: floci is equivalent to changing base-url from http://localhost:4566 to http://floci:4566.

Example — Docker Compose multi-container setup:

environment:
  FLOCI_HOSTNAME: floci   # matches the compose service name

See Docker Compose — Multi-container networking for a full example.

Full Reference

The block below mirrors src/main/resources/application.yml, it's the effective set of keys Floci ships with. Some supported keys are omitted here (for example floci.init-hooks.*) but can still be provided via YAML or environment variables.

floci:
  max-request-size: 512              # Max HTTP request body size in MB
  base-url: "http://localhost:4566"  # Used to build response URLs (SQS QueueUrl, SNS endpoints, etc.)
  # hostname: ""                     # When set, overrides the host in base-url for multi-container Docker
  default-region: us-east-1
  default-account-id: "000000000000"

  storage:
    mode: memory                      # memory | persistent | hybrid | wal
    persistent-path: ./data
    wal:
      compaction-interval-ms: 30000
    services:
      ssm:
        flush-interval-ms: 5000
      dynamodb:
        flush-interval-ms: 5000
      sns:
        flush-interval-ms: 5000
      lambda:
        flush-interval-ms: 5000
      cloudwatchlogs:
        flush-interval-ms: 5000
      cloudwatchmetrics:
        flush-interval-ms: 5000
      secretsmanager:
        flush-interval-ms: 5000
      acm:
        flush-interval-ms: 5000
      opensearch:
        flush-interval-ms: 5000

  auth:
    validate-signatures: false               # Set to true to enforce AWS SigV4 validation
    presign-secret: local-emulator-secret    # HMAC secret for S3 pre-signed URL verification

  services:
    ssm:
      enabled: true
      max-parameter-history: 5               # Max versions kept per parameter

    sqs:
      enabled: true
      default-visibility-timeout: 30         # Seconds
      max-message-size: 262144               # Bytes (256 KB)

    s3:
      enabled: true
      default-presign-expiry-seconds: 3600

    dynamodb:
      enabled: true

    sns:
      enabled: true

    lambda:
      enabled: true
      ephemeral: false                        # true = remove container after each invocation
      default-memory-mb: 128
      default-timeout-seconds: 3
      docker-host: unix:///var/run/docker.sock
      runtime-api-base-port: 9200             # Port range for Lambda Runtime API
      runtime-api-max-port: 9299
      code-path: ./data/lambda-code           # Where ZIP archives are stored
      poll-interval-ms: 1000
      container-idle-timeout-seconds: 300     # Remove idle containers after this
      region-concurrency-limit: 1000          # Concurrent executions ceiling per region
      unreserved-concurrency-min: 100         # Minimum unreserved capacity PutFunctionConcurrency must leave

    apigateway:
      enabled: true

    apigatewayv2:
      enabled: true

    iam:
      enabled: true
      enforcement-enabled: false        # Set to true to enforce IAM policies on all requests

    elasticache:
      enabled: true
      proxy-base-port: 6379
      proxy-max-port: 6399
      default-image: "valkey/valkey:8"

    rds:
      enabled: true
      proxy-base-port: 7001
      proxy-max-port: 7099
      default-postgres-image: "postgres:16-alpine"
      default-mysql-image: "mysql:8.0"
      default-mariadb-image: "mariadb:11"

    eventbridge:
      enabled: true

    scheduler:
      enabled: true

    cloudwatchlogs:
      enabled: true
      max-events-per-query: 10000

    cloudwatchmetrics:
      enabled: true

    secretsmanager:
      enabled: true
      default-recovery-window-days: 30

    kinesis:
      enabled: true

    kms:
      enabled: true

    cognito:
      enabled: true

    stepfunctions:
      enabled: true

    cloudformation:
      enabled: true

    acm:
      enabled: true
      validation-wait-seconds: 0              # Seconds before transitioning PENDING_VALIDATION → ISSUED

    ses:
      enabled: true

    opensearch:
      enabled: true
      mode: mock                              # mock | real
      default-image: "opensearchproject/opensearch:2"
      proxy-base-port: 9400
      proxy-max-port: 9499

    ec2:
      enabled: true

    ecs:
      enabled: true
      mock: false                             # true = tasks go to RUNNING without Docker (useful for CI)

    appconfig:
      enabled: true

    appconfigdata:
      enabled: true

    ecr:
      enabled: true
      registry-image: "registry:2"
      registry-container-name: floci-ecr-registry
      registry-base-port: 5100
      registry-max-port: 5199
      data-path: ./data/ecr
      tls-enabled: false
      keep-running-on-shutdown: true
      uri-style: hostname                     # hostname | path

Initialization hooks

floci.init-hooks.* is accepted as an override but is not declared in the shipped application.yml. See Initialization Hooks for the full list of keys (shell-executable, timeout-seconds, shutdown-grace-period-seconds) and their defaults.

Service Limits

All keys in this table are declared on EmulatorConfig and accept environment variable overrides via the FLOCI_ prefix.

Variable Default Description
FLOCI_MAX_REQUEST_SIZE 512 Max HTTP request body size in MB
FLOCI_DEFAULT_REGION us-east-1 Default AWS region used in ARNs and response URLs
FLOCI_DEFAULT_AVAILABILITY_ZONE us-east-1a Default AZ reported by EC2, RDS, and other AZ-aware services
FLOCI_DEFAULT_ACCOUNT_ID 000000000000 Default AWS account ID used in ARNs
FLOCI_ECR_BASE_URI public.ecr.aws Base URI used when pulling container images (e.g. Lambda)
FLOCI_SERVICES_SSM_MAX_PARAMETER_HISTORY 5 Max parameter versions kept
FLOCI_SERVICES_SQS_DEFAULT_VISIBILITY_TIMEOUT 30 Default visibility timeout (seconds)
FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE 262144 Max message size (bytes)
FLOCI_SERVICES_S3_DEFAULT_PRESIGN_EXPIRY_SECONDS 3600 Pre-signed URL expiry
FLOCI_SERVICES_DOCKER_NETWORK (unset) Shared Docker network for Lambda, RDS, ElastiCache containers
FLOCI_SERVICES_ECS_MOCK false Skip Docker; tasks go straight to RUNNING (useful for CI)
FLOCI_SERVICES_ECS_DOCKER_NETWORK (unset) Docker network for ECS task containers
FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB 512 Default memory (MB) when task definition omits it
FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS 256 Default CPU units when task definition omits it
FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED false Enforce IAM identity-based policies on every request when true

Per-queue SQS redrive policy (maxReceiveCount) is configured at queue creation time via SetQueueAttributes / CreateQueue, not as a global default.

FLOCI_DEFAULT_AVAILABILITY_ZONE and FLOCI_ECR_BASE_URI are declared in EmulatorConfig but not in the shipped application.yml, so they fall through to the @WithDefault values above when unset.

Disabling Services

Set enabled: false for any service you don't need. Disabled services return a ServiceUnavailableException rather than silently ignoring calls.

floci:
  services:
    cloudformation:
      enabled: false
    stepfunctions:
      enabled: false