Allen Sanborn c6b8a70ea8 fix(ecs): a service reaches steady state, and a finished deployment stays finished (#4694)
* fix(ecs): name a service revision by the deployment's task set id

A service created against Floci never reached STABLE for a client that asked
to wait for it. `aws_ecs_service` with `wait_for_steady_state` sat on tfPENDING
for its whole 20-minute timeout while the emulator reported the service ACTIVE,
at its desired count, with one PRIMARY deployment whose rolloutState was
COMPLETED and one RUNNING task. Six of the first sixteen terraform-aws-ecs
Terratest suites failed that way, three burning the full waiter.

Nothing in DescribeServices was stuck; every field that waiter used to read
settles in about ten seconds. Since provider 6.x a service under the ECS
deployment controller whose PRIMARY deployment started after the operation is
not judged from DescribeServices at all. The provider reads deployments[0].id,
which is "ecs-svc/<taskSetId>", then takes the ListServiceDeployments brief
whose targetServiceRevisionArn *contains that id*, and polls
DescribeServiceDeployments on it:

    if strings.Contains(aws.ToString(deployment.TargetServiceRevisionArn), taskSetID)

AWS makes that join work by naming the service revision with the very id the
deployment reports -- its own docs pair "ecs-svc/1485800978477494678" with
".../service-revision/<cluster>/<service>/1485800978477494678". Floci minted
the two from independent UUIDs, so the join matched nothing,
findPrimaryDeploymentARN returned nil, and that path returns tfPENDING with no
error, forever. The emulator's request log for one hung apply shows 50
ListServiceDeployments calls and zero DescribeServiceDeployments: the provider
never got past the join. DescribeServiceDeployments itself was fine all along.

recordServiceDeployment now names the revision by the deployment's task set id.

The status that join leads to has to mean something too, so it is derived for
the deployment a service is currently on, the same way deploymentsFor derives
rolloutState: IN_PROGRESS until runningCount has reached desiredCount,
SUCCESSFUL once it has. Recording every deployment SUCCESSFUL with a finishedAt
at create time, as before, would have turned wait_for_steady_state into a wait
that can never fail -- a silent false pass in place of a loud timeout -- and
terraform-aws-ecs's own failure tests deliberately break the container and
assert the apply errors. A deployment the service has moved off keeps what it
was last recorded with. What that derivation still does not model -- a terminal
failure state, rollback, closing out superseded deployments -- is filed
separately.

Measured end to end on the example that timed out: the service now converges in
13s, with one ListServiceDeployments and seven DescribeServiceDeployments, so
the wait is gated on real convergence rather than passing instantly.

* test(ecs): say what the zero-desired deployment test guards

One of the five tests added with the fix passes on the build the bug was found
on, because there every deployment was born SUCCESSFUL and a zero-desired
service was trivially SUCCESSFUL too. That makes it a guard rather than a
repro, and an undocumented guard reads as slack: the next reader counts five
tests, sees four bite, and assumes the fifth is padding.

Measured rather than asserted. Mutating settleStatus to refuse to call a
zero-desired service converged -- adding `&& svc.getDesiredCount() > 0`, the
shape a defensive "nothing was asked for, so nothing succeeded" slip takes --
turns it red with `expected: <SUCCESSFUL> but was: <IN_PROGRESS>` while both
desiredCount-1 tests in the same class stay green. It is the cheap cousin of
deriving the status on a reconciler tick instead of at read time, which for a
service that never needs a tick amounts to the same thing.

The comment also records that it is not independent coverage: the same mutation
reddens this fix's integration twin and the pre-existing
EcsFargateEdgeCaseIntegrationTest.aServiceDeploymentPointsAtTheRevisionItDeployed,
both of which use desiredCount 0 as well. It is kept because it is the only one
of the three whose failure names the condition; the others report a wire
assertion.

* fix(ecs): settle a deployment on its own tasks, not the service's

A service's runningCount counts every RUNNING task it owns, including the ones
still draining from the deployment a rolling change replaced. Deriving a
deployment's status from it reported a task-definition change finished the
instant UpdateService returned, on the strength of the OLD revision's task. The
provider joins to that deployment and stops polling on its first tick, so
wait_for_steady_state on an image change -- the most common real use of the
flag -- returned immediately and a new image that could not start read as
stable.

The create path in the preceding commit was right because a new service owns no
tasks yet, so the service-wide count and the deployment's own count agree. They
diverge exactly when a deployment replaces another, which is the case that
commit did not test. Adding that test is what found this.

runningOnCurrentDeployment counts the service's RUNNING tasks that are not
stale for the current deployment, reusing the ownedBy and isStaleForDeployment
predicates the reconciler already applies. It recomputes rather than caching
what the reconciler derived one line above where it sets runningCount: that
value is a fact about the last tick, and a deployment is read on demand between
ticks -- right after UpdateService, which is the moment that matters.

Applied to the two other places that asked the same question of the wrong
number, both of which predate this branch:

  deploymentsFor  rolloutState, and the Deployment's own runningCount, which is
                  per-deployment in AWS. Left alone it would overstate the count
                  mid-rollout and contradict the ServiceDeployment resource that
                  is now derived correctly -- two Floci views of one deployment
                  disagreeing is worse than both being wrong together.
  eventsFor       the steady-state event, emitted on the same condition.

Measured as a side effect: convergence is now visible one tick earlier, because
the count is taken from the tasks at read time instead of from runningCount,
which the reconciler sets from a snapshot taken before it launches anything. A
test comment that documented the old one-tick lag is updated.

Adjacent cases now covered: a deployment whose task dies goes back to
IN_PROGRESS and withdraws its finishedAt; two updates with no tick between them
settle only the newest; scaling to zero reports converged while the task is
still draining, which is recorded as measured behaviour rather than asserted as
ideal, since AWS's waiter compares with == and would hold it pending.

* fix(ecs): make a finished deployment terminal, and settle onto a copy

Two faults with one root: a deployment's status was derived from a live count
on every read, with nothing to stop it moving.

SUCCESSFUL is terminal in AWS. A completed deployment does not un-complete
because the service later became unhealthy, and finishedAt records when the
deployment finished, not the last time it was asked about. Deriving afresh let
tasks dying afterwards flip a finished record back to IN_PROGRESS, blank a
finishedAt it had already published, and stamp a new one on recovery. Scoping
the count to the deployment's own tasks does not fix this -- when its own tasks
die that count drops too -- so the transition now runs once and never reverses.
Measured both ways: the new test goes red against the preceding commit, which
has the scoped count but no latch, and that commit's update-path test goes red
against the one before it, which has the latch's absence but the wrong count.
Neither fix subsumes the other.

Reads no longer hand out the stored record. settleStatus writes to it and the
response is serialised after it returns, so one request's settle could land
inside another's serialisation; ServiceDeployment's fields are plain and
non-volatile, and a reader could see status=SUCCESSFUL beside a finishedAt that
had not arrived. The transition and the copy now happen under one lock, so a
caller sees a single consistent moment.

Also reverts this branch's changes to deploymentsFor and eventsFor. They were
made to stop rolloutState contradicting the ServiceDeployment resource, but a
terminal SUCCESSFUL makes the two legitimately diverge when tasks die later --
the record stays finished, the live rollout state does not -- so the
consistency argument for touching them no longer holds. Reverting also restores
the property that DescribeServices output is byte-identical to upstream for
services that never ask to wait, which keeps this branch to the one API the bug
is about. The same miscount is still there in rolloutState, predates this
branch, and is recorded on floci-n5kb.

The task scan sits after the is-this-the-current-deployment guard, so a call
costs at most one scan however many deployments it returns, and none once one
has latched.

* fix(ecs): derive rolloutState from the deployment's own tasks too

Reinstates the deploymentsFor and eventsFor half that the previous commit
reverted, because the reason given for reverting it was wrong.

That reason was: once SUCCESSFUL latches, the deployment record and
rolloutState legitimately diverge when tasks die later, so "keep the two views
consistent" is no longer a reason to touch rolloutState. The first half is
true; the conclusion does not follow. It generalises from the one case where
divergence is correct to the case that actually matters, and they are different
questions.

Late divergence is two questions with two right answers: the record is history
and stays finished, rolloutState is live and follows the service. Divergence
DURING a rollout is one question with two answers. Immediately after a
task-definition change, both are describing a rollout that has not started --
and with rolloutState still derived from the service-wide count it reported
COMPLETED while the record correctly said IN_PROGRESS. A client reading
DescribeServices was told the rollout was done when it had not begun, and had
no way to tell which of Floci's two answers to trust.

So the quantity is corrected in all three places that ask the question, while
the latching stays only on the record, where it belongs. Deployment.runningCount
becomes this deployment's count, which is what the field means in AWS; a count
that means something different in two places is the same class of bug as the
one being fixed.

Cost is bounded by the latch rather than by this change: the SUCCESSFUL test is
the first conjunct in settleStatus and && short-circuits, so a settled
deployment never runs the scan, and the is-this-the-current-deployment guard
skips it for the rest. A converged service pays what it always did.

Adds a test pinning both directions: the two views agree while a rollout is in
flight, and the steady-state event stays withheld until it lands.

* test(ecs): pin the two behaviours that survived their own mutants

Both new behaviours on this branch were asserted from a state where the defect
they describe cannot manifest, so removing either production change left the
suite green.

The agree test changed the task definition one reconciler tick after create.
reconcileService sets svc.runningCount from a snapshot taken before it launches,
so one tick short of a steady state that field is still 0 -- and the buggy
derivation, which reads it, gives the right answer by accident. Any service
alive longer than one 5-second tick is past that window, which is every service
anyone actually changes an image on. It now ticks twice and asserts
runningCount == 1 as an explicit precondition, so a future change to tick timing
cannot quietly move it back into the window where it stops testing anything.

The task-death test only re-read the record after the tasks died, when the
converged branch is not taken, so it never exercised the latch itself. Deleting
the already-SUCCESSFUL clause left it green while finishedAt was re-stamped on
every read of a converged deployment. It now re-reads once while still
converged, before stopping the task.

Measured with each production change reverted in turn:
  deploymentsFor/eventsFor -> svc.getRunningCount()
    expected: <IN_PROGRESS> but was: <COMPLETED>
  the SUCCESSFUL clause deleted from settleStatus
    expected: <2026-09-29T18:01:10.537673Z> but was: <...538869Z>

Also from review, three fixes and one correction:

settleStatus folds its guard into the synchronized condition, so every copy is
taken under the lock. "Current" is decided against a deploymentId UpdateService
can mint at any moment, so two threads can disagree about which deployment is
current and the unsynchronised early-return copy could have run beside the
write -- the torn record the lock exists to prevent.

runningOnCurrentDeployment resolves the task definition the same way the
reconciler does. isStaleForDeployment falls back to comparing that against a
task's ARN for tasks minted before deployment ids were stamped, so passing the
raw family reference would have marked every task stale and reported a running
service as having none. Extracted resolvedTaskDefinitionArn, shared by both
callers; the reconciler still caches the resolution, the read path does not,
because a read has no business writing to the service.

currentServiceDeployment now settles like every other read instead of handing
out the stored record. Its caller reads only the two ARN fields, so this was
safe by accident rather than by construction, and copyOf's contract is that no
read returns the stored object. That makes it a third read path depending on
the copy, which is noted at the call site: the copy is load-bearing there, not
tidiness.

The cost note is corrected. The short-circuit bound covers settleStatus alone;
deploymentsFor and eventsFor call runningOnCurrentDeployment unconditionally,
because there is nothing to latch on the live side. The comment said "none at
all once one has latched", which was true of the method and false of the
response.

* docs(ecs): replace the guessed scan cost with a measured one

The note said deploymentsFor and eventsFor call runningOnCurrentDeployment
"unconditionally". True of deploymentsFor, which is a bare call. False of
eventsFor, whose call is the last disjunct of an || chain and so is skipped
entirely for a service that is absent or not ACTIVE -- checkable by reading the
three lines, which is how review caught it.

The number was guessed too. Measured instead, by counting calls to
runningOnCurrentDeployment per DescribeServices per service on a clean tree:

  ACTIVE, first poll after a create or a rollout   3   (1 + 1 + 1)
  ACTIVE, every later poll of a settled service    2   (1 + 1 + 0)
  not ACTIVE, or the service is gone               0

The third term is currentServiceDeployment, which settles and therefore scans
until the current deployment latches and never again -- the poll that reads 1 is
the poll that latches it. So the steady-state cost a polling waiter actually
pays is 2, not the 3 of its first call, and an earlier claim of "none at all
once one has latched" was true only of settleStatus in isolation.

An earlier attempt at this measurement read 0 for deploymentsFor, which is
impossible against a bare call, and that impossibility is what exposed a
corrupted worktree rather than a surprising result. Those numbers were voided.
This run refuses to start unless the tree is clean and restores with git
checkout, so the baseline is a commit rather than a byte copy taken at an
unknown moment.

* docs(ecs): the unlatched cost is every poll, not the first one

The row read "first poll after a create or a rollout", which implies later
polls of a rollout in progress cost 2. They cost 3. A deployment stays unlatched
until it converges, so a slow rollout -- or one that never converges -- pays the
third scan on every poll for its whole duration, which is precisely when a
waiter is polling hardest.

The measured numbers were right and the prose beneath them was right
("scans until the current deployment latches and never again"); only the label
contradicted both. Worth recording that it survived into the commit whose
purpose was to replace a guessed cost with a measured one: measuring the right
thing does not stop you describing it wrongly, and the description is what the
next reader acts on.

* style(ecs): drop em dashes, and the unreachable region literal

Two upstream policy gates on #4694, neither a defect in behaviour.

AGENTS.md prohibits em dashes in any content. Thirteen in lines this branch
adds, replaced with colons, commas or periods as each sentence needed. Em
dashes on lines the branch does not touch are left alone, so the diff stays
about this change.

The partition gate flagged a new region literal in serviceRegion, the helper
added for resolvedTaskDefinitionArn:

    return regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1";

It was copied from the sibling taskRegion, which upstream annotated with
// partition-literal in #4494. Mirroring that annotation would have been the
cheap route and the wrong one: the guard is unreachable. Nothing constructs an
EcsService without a resolver, and the class dereferences regionResolver
unguarded in the create paths, so a null one fails long before this line. The
literal is therefore dead code that is also wrong in any non-default partition,
which is the worst combination available. Routed through the resolver instead,
which is the gate's own first suggestion, and the dead branch is gone rather
than documented. taskRegion is left as upstream wrote it.

The REGION = "us-east-1" constant in the new test matches four existing ECS
test classes and was not flagged; test fixtures are not partition-sensitive.

* style(ecs): import Map rather than qualifying it inline

AGENTS.md wants the import. Every other ECS test class already does it this
way.

* fix(ecs): count every task a DAEMON service owns, stale or not

Scoping the count to the current deployment is right for REPLICA and wrong for
DAEMON, and left unqualified it created for DAEMON exactly the hang this branch
removes for REPLICA.

reconcileDaemonService has no notion of staleness anywhere in it: no
deploymentId, no task-definition comparison. It decides which tasks to keep
purely by which container instances they cover, so after a task-definition
change the old revision's task holds its slot and no replacement is launched.
A deployment-scoped count therefore sits at zero for ever.

Measured across four reconciler ticks on a DAEMON service with one active
container instance, before this commit and with the count reverted to main's:

  after task-def change   this branch             main
  tick 1 .. tick 4        IN_PROGRESS / nofin     COMPLETED / SUCCESSFUL
                          events 0                events 1
  tasksRunning = 1, and it is the OLD revision's task, throughout

So wait_for_steady_state on a DAEMON image change would have hung until its
timeout where main returned promptly. Counting every owned RUNNING task keeps
DAEMON exactly as main behaves, which makes this branch a strict improvement:
REPLICA fixed, DAEMON unchanged.

This is a mitigation, not a claim that DAEMON is correct. Reporting a
deployment finished while the previous revision is what is running is wrong,
and the real fault is that DAEMON services never roll on a task-definition
change, which is a pre-existing reconciler defect this branch only made
visible. Fixing it means changing daemon scheduling, which does not belong in
a change about when a deployment is finished; it is filed separately.

The test pins the limitation as well as the fix: it asserts the surviving task
is still the old revision's, so the day DAEMON rolling is implemented, the test
says so rather than silently passing.

* docs(ecs): the DAEMON count matches main from tick one, not exactly

The comment claimed counting stale tasks "keeps DAEMON exactly as it behaves on
main". Off by one tick. An identical probe across create, two ticks, a
task-definition change and four more ticks matches main on every row from tick
one onward, and differs on exactly one: a DAEMON deployment with no tasks
running yet reads IN_PROGRESS here and SUCCESSFUL on main.

That difference is the birth-state fix applied uniformly, which is this
branch's whole subject, so DAEMON is a strict improvement rather than merely
unchanged. "Exactly" claimed both less and more than the measurement supports.

The same correction cannot be made to the preceding commit's message, which
carries the original wording. Force-push is barred here and rightly so, so it
is corrected here instead: read that message with this commit beside it.

The test's note on why the limitation is pinned is also sharpened. It said the
assertion stops a mitigation outliving its reason. The coupling is stronger
than that: once DAEMON rolls, counting stale tasks would reproduce on DAEMON
the exact REPLICA bug this branch removes, so the DAEMON branch of the count
has to come out at the same moment, and this assertion is what forces it.

* fix(ecs): stop a deployment the next one supersedes

settleStatus finishes only the deployment a service is currently on, so
a deployment superseded before its tasks converged could never be moved
again: it stayed IN_PROGRESS with no finish time for the life of the
emulator, describing a rollout that could no longer happen. Listing a
service's deployments returned a growing pile of them apparently in
flight at once, and a listing filtered on IN_PROGRESS returned every
rollout the service had ever abandoned.

Recording a deployment now lands the ones it takes over from in STOPPED,
which is the status AWS uses for a deployment that ended without
completing, stamping finishedAt and updatedAt. Only a deployment still
in progress is moved, so one that had already reached SUCCESSFUL keeps
its status and the instant it finished at: that record is history, not
something a later rollout rewrites. The scan is scoped to the one
service ARN.

The write is made under the same monitor settleStatus writes under,
because the two race: a read settling the outgoing deployment can run
beside the update minting its replacement. Both transitions now require
IN_PROGRESS, so whichever lands second finds a terminal status and
leaves it alone and neither can undo the other. That tightens
settleStatus's own guard from "not SUCCESSFUL" to "still IN_PROGRESS",
which is the same condition for every status it can legally advance.

* fix(ecs): stop the deployment a deleted service leaves unfinished

Superseding a deployment was one of the two ways a deployment could be
put permanently beyond settleStatus. This is the other. settleStatus
finishes a deployment only while its service is ACTIVE, and deleteService
sets the service INACTIVE without touching the deployment records at all,
so deleting a service before its first rollout converged left that
deployment IN_PROGRESS with no finish time for ever. No later update
could supersede it, because there are no later updates on a deleted
service. ListServiceDeployments filtered on IN_PROGRESS returned it
indefinitely, which is the same symptom a superseded deployment had,
reached through a different door.

Both routes now go through one helper, which stops only the deployments
of the one service that are still in progress.

Deliberately narrower than AWS, which documents that it "deletes the
service deployment when you delete a service". Stopping the records
removes them from an IN_PROGRESS listing, which is the actual harm,
without turning a DescribeServiceDeployments a client is mid-poll on into
a failure. Deleting them would match AWS and destroy history a client may
still be reading, which is a larger and less reversible change than this
fix warrants; full parity is tracked separately.

Also adds stoppedAt and statusReason to the deployment model, the
response writer and the detached copy every read hands back. Both are
members of AWS's ServiceDeployment shape and neither was written at all,
so a client asking when a stopped deployment ended, or why, got nothing.
AWS files STOPPED under its "Completed" lifecycle stage, so a stopped
record carries finishedAt as well as stoppedAt; a deployment that is
running or that succeeded carries neither field, absent rather than null.

* docs(ecs): drop private tracker ids from javadoc

Four javadoc references named issues in a private tracker, so a reader of
this code upstream could not resolve any of them. The behaviour each one
described is stated in the surrounding prose already, which is where it
belongs: a comment has to stand on its own for whoever reads it next.

* test(ecs): name the deployment asserted on, never its index

The superseded-deployment assertion read the listing's index 1 and 2.
listServiceDeploymentsDetailed sorts on createdAt and List.sort is
stable, so three deployments minted inside one clock tick share a
timestamp and their order in that listing is ConcurrentHashMap iteration
order. The assertion held here only because Instant.now() resolves finer
than the cost of minting a deployment on this machine; where the clock is
coarser it would pass or fail by hash order. Each record is now selected
by its own task set id, which is what the rest of the class already does
and what its javadoc already claimed of the whole file.

Also records why the supersede pass runs before the new deployment is
published rather than after, since that ordering looks arbitrary and is
not: two concurrent UpdateService calls can leak one stale IN_PROGRESS
record this way, whereas publishing first and stopping everything but
self lets one caller stop the current deployment and hang a steady-state
wait, which is the failure this branch exists to remove. Locking is not
the answer at this level, because updateService already mutates the
shared service model unsynchronised.

Drops an unreachable null check on the service ARN: the caller
dereferences the same value before calling in, so a null cannot arrive.

* fix(ecs): stop a deleted service's deployments before zeroing its count

deleteService wrote status INACTIVE and desiredCount 0, then stopped the
service's unfinished deployments several statements later. Both fields are
plain non-volatile fields of a service model shared with every reader, and
settleStatus reads them under synchronized (deployment), a monitor nothing
takes for the service. So in that window a reader could see the new
desiredCount of 0 beside a status it still read as ACTIVE, and zero
running tasks satisfies the convergence test trivially: the deployment
latched SUCCESSFUL, reporting a rollout that never happened as having
succeeded. The already-terminal guard cannot help, because the record is
still IN_PROGRESS at that point and its revision ARN still matches.

Stopping the records between the two setters closes the window rather than
narrowing it. A reader arriving earlier still sees the honest pre-delete
desiredCount, so it can only finish a deployment that really converged.
One arriving later finds the record already STOPPED, so the guard blocks
the latch whatever it sees of the service. The dangerous pairing becomes
observable only once the record is terminal anyway.

The call is safe in its new position because the helper reads nothing
about the service: it takes an ARN, a timestamp and a string, and branches
only on each deployment's own status. It stays below the force-flag
validation, so a request that throws still stops nothing.

The ordering is a correctness constraint rather than a style choice, and
nothing in the code said so, so the call site now does: moving
setDesiredCount up, or the helper back down, silently reopens this.

Reasoned, not pinned. The window is a memory-visibility race between two
threads, so single-threaded execution cannot distinguish the two orders at
all: both leave identical state. Reverting the move fails no test.

* test(ecs): identify the stopped deployment after the delete, not before

The wire test read DescribeServices to find the deployment before deleting
the service, and its javadoc claimed determinism on the grounds that
nothing read the service in that window. That read was the window. Every
response serialising a service settles that service's current deployment,
so a reconciler tick landing between the create and the read would launch
the task, the read would latch the deployment SUCCESSFUL, and the delete
would then correctly leave a terminal record alone, failing the
assertions. A few milliseconds against a 5000ms period.

The service is created once and never updated, so it has exactly one
deployment and needs no join to identify. Deleting first and listing
afterwards removes the read, and a terminal record cannot change under a
read anyway.

One window remains and is now written down rather than papered over: a
tick between CreateService putting the service in the map and that same
response being serialised would still latch it. Sub-millisecond, and not
closable from a test without stubbing the clock. The behaviour is pinned
without timing in the unit suite; this test exists for the wire mapping.

Also restores the null check on the service ARN in the stop helper. The
reason given for removing it was only half right: recordServiceDeployment
does dereference that field first, but deleteService does not, so at that
call site the check was load-bearing and removing it turned a silent
no-op into an NPE inside DeleteService. A service model can arrive by
deserialisation from the store rather than through createService, so a
non-null ARN is not an invariant, and ownedBy guards the same field for
the same reason.

* fix(ecs): settle the outgoing deployment when UpdateService supersedes it

A converged deployment was only marked SUCCESSFUL when something read it
while it was still current, so an update with no read in between left it
STOPPED. UpdateService now settles it first, before it changes the desired
count or task definition, which the settle judges against.

* docs(ecs): trim the deployment comments to what the code needs

Drops branch history and private tracker references, and corrects the
recordServiceDeployment Javadoc, which described AWS's revision ARN form
rather than the service-revision/<id> one it builds.

* fix(ecs): DeleteService settles a converged deployment before stopping it

A deployment whose tasks were up when the service was force-deleted was
marked STOPPED unless something had read it first. DeleteService now
settles it against the service as it stands, as UpdateService does.

The integration test that stops a deployment through a delete retries on
a fresh service when the reconciler converges it first, instead of
failing on that race.
2026-09-30 13:12:20 -04:00
2026-09-15 04:56:10 +00:00
2026-03-15 17:43:56 -05:00
2026-03-24 00:41:47 -05:00

Floci Floci

Any Cloud. Locally.
Light, fluffy, and always free
No account. No auth token. No feature gates. Just docker compose up.

Latest Release Build Status Docker Pulls Docker Image Size License: MIT GitHub Stars

Quick Start · Features · Services · SDKs · Testcontainers · Migration · Docs


What is Floci?

Floci is a free, open-source local AWS emulator for development, testing, and CI.

It gives you AWS-shaped services on your machine without requiring a cloud account, an auth token, or paid feature gates. Point your AWS SDK, CLI, Terraform, CDK, OpenTofu, or test suite at http://localhost:4566 and keep your existing workflows.

Already using LocalStack? Floci is a drop-in replacement: swap the image and keep going. See Migrating from LocalStack.

Floci is the AWS member of the Floci emulator family, named after floccus, the cloud formation that looks like popcorn.

Emulator Cloud Port
floci AWS 4566
floci-az Azure 4577
floci-gcp GCP 4588
floci-oci OCI 4599

Quick Start

The fastest way to run Floci is with the official CLI

floci start

Export the AWS environment variables:

eval $(floci env)

Use your existing AWS tools normally:

aws s3 mb s3://my-bucket

aws dynamodb create-table \
  --table-name demo-table \
  --attribute-definitions AttributeName=pk,AttributeType=S \
  --key-schema AttributeName=pk,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

aws dynamodb list-tables

Watch it run

This short demo shows the CLI flow: start Floci, export the local AWS environment, run standard AWS CLI commands, and stop the emulator.

https://github.com/user-attachments/assets/b55714dc-ef36-40ae-a734-cd2cadc288a8

All AWS services are available at http://localhost:4566. Any published AWS region works, in every partition. Credentials can be any non-empty values unless you explicitly enable stricter service-specific auth checks.

Prefer Docker Compose?

Create a compose.yaml file:

services:
  floci:
    image: floci/floci:latest
    ports:
      - "4566:4566"

Start Floci:

docker compose up

Then configure your AWS environment manually:

export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
Using the old hectorvent/floci image?

Update your image name:

# Before
image: hectorvent/floci:latest

# After
image: floci/floci:latest

The old hectorvent/floci repository no longer receives updates.

Web Console

Floci ships a browser console for inspecting the resources in your local emulator.

Open it at: http://localhost:4566/_floci/ui

Nothing runs at boot. The first request pulls the console image, starts it as a sidecar container on Floci's Docker network, hands it Floci's own reachable address plus the standard AWS environment, polls its health endpoint, and redirects the browser once it reports it can reach Floci. The sidecar's port is bound by Docker, so it needs no ports: entry of your own, and its logs are streamed into CloudWatch Logs under /floci/ui.

Starting a container needs the Docker socket:

services:
  floci:
    image: floci/floci:latest
    ports:
      - "4566:4566"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
Variable Default Description
FLOCI_SERVICES_UI_ENABLED true Enable the console sidecar
FLOCI_SERVICES_UI_IMAGE floci/floci-ui:latest Console image to run
FLOCI_SERVICES_UI_CONTAINER_NAME floci-ui Name of the sidecar container
FLOCI_SERVICES_UI_PORT 4500 Host port the console is published on
FLOCI_SERVICES_UI_BIND_ADDRESS (none) Host interface that port is published on. Unset publishes on every interface; set 127.0.0.1 when Floci's own port is loopback-only
FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN false Leave the sidecar running when Floci stops

Running a different console

The console is not fixed to the one Floci ships. Any console implementing the Floci console contract runs with nothing but an image name: listen on the port in PORT, serve GET /api/health, talk to Floci at AWS_ENDPOINT_URL.

environment:
  FLOCI_SERVICES_UI_IMAGE: acme/my-console:1.0

A console that differs from the contract's defaults says so in its own io.floci.console.* image labels, so its operators do not have to. StackPort, for example, listens on 8080 rather than 4500; on an image that predates the labels, say it by hand:

environment:
  FLOCI_SERVICES_UI_IMAGE: davireis/stackport:latest
  FLOCI_SERVICES_UI_CONTAINER_NAME: floci-stackport
  FLOCI_SERVICES_UI_PORT: "8080"
  FLOCI_SERVICES_UI_INTERNAL_PORT: "8080"

Floci Dash is another. It honours PORT, so only the two things it does differ on need naming:

environment:
  FLOCI_SERVICES_UI_IMAGE: ghcr.io/ofsazib/floci-dash:latest
  FLOCI_SERVICES_UI_CONTAINER_NAME: floci-dash
  FLOCI_SERVICES_UI_ENDPOINT_ENV: FLOCI_URL
  FLOCI_SERVICES_UI_STATUS_PATH: /api/healthz

The endpoint itself is never configured by hand: Floci resolves its own reachable address at start time and injects it as AWS_ENDPOINT_URL.

Full reference: Web Console and Console Contract v1.

Features

Local AWS without the cloud account

Run AWS-compatible services locally without an AWS account, auth token, or paid feature gates.

Real Docker where fidelity matters

Lambda, RDS, Neptune, ElastiCache, MSK, ECS, EC2, EKS, OpenSearch, CodeBuild, and Managed Service for Apache Flink use real Docker-backed execution instead of shallow mocks.

Drop-in AWS compatibility

Point standard AWS clients at http://localhost:4566. Existing credentials, regions, SDKs, CLI commands, and IaC workflows stay familiar.

Terraform can provision AWS-shaped resources locally through Floci using the standard HashiCorp AWS provider. See the Terraform with Floci guide for provider configuration, resource examples, and optional emulated S3 state.

Fast enough for CI

The native image starts in milliseconds and keeps idle memory low, making it practical for local development and test pipelines.

Configurable persistence

Choose from in-memory, persistent, hybrid, and write-ahead log storage depending on the durability profile you need.

Why Floci?

LocalStack's community edition sunset in March 2026, requiring auth tokens and freezing security updates. Floci is the no-strings-attached alternative.

Capability Floci LocalStack Community
Auth token required No Yes
Security updates Yes Frozen
Startup time ~24 ms ~3.3 s
Idle memory ~13 MiB ~143 MiB
Docker image size ~90 MB ~1.0 GB
License MIT Restricted
API Gateway v2 / HTTP API Yes No
Cognito Yes No
RDS, ElastiCache, MSK Real Docker No
Neptune (graph DB + Gremlin WebSocket) Real Docker No
DocumentDB (MongoDB-compatible) Real Docker No
ECS, EC2, EKS Real Docker No
CodeBuild Real Docker execution No
Native binary ~40 MB No

Broad AWS coverage. Free forever. See the Services Overview for the full list of emulated services.

Architecture Overview

flowchart LR
    Client["AWS SDK / CLI"]

    subgraph Floci ["Floci, port 4566"]
        Router["HTTP Router\nJAX-RS / Vert.x"]

        subgraph Stateless ["Stateless Services"]
            A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM · Config · CloudTrail\nAPI Gateway · AppSync · ELB v2 · Auto Scaling\nElastic Beanstalk · CodeDeploy · CodePipeline · Backup · FIS · Bedrock Runtime · Bedrock AgentCore · Route53 · Transfer"]
        end

        subgraph Stateful ["Stateful Services"]
            B["S3 · DynamoDB\nDynamoDB Streams"]
        end

        subgraph Containers ["Container Services"]
            C["Lambda\nElastiCache\nRDS\nNeptune\nECS\nEC2\nMSK\nEKS\nOpenSearch\nCodeBuild\nManaged Flink"]
            D["Athena -> floci-duck\nDuckDB sidecar"]
        end

        Router --> Stateless
        Router --> Stateful
        Router --> Containers
        Stateless & Stateful --> Store[("StorageBackend\nmemory · hybrid · persistent · wal")]
    end

    Docker["Docker Engine"]
    Client -->|"HTTP :4566\nAWS wire protocol"| Router
    Containers -->|"Docker API\nIAM / SigV4 auth"| Docker

Supported Services

Floci supports local emulation for application services, data services, eventing, identity, infrastructure, billing, and container-backed workloads.

Category Services
Core app services S3, SQS, SNS, DynamoDB, Lambda, Lambda MicroVMs, IAM, STS, KMS, Secrets Manager, SSM
Events and workflows EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP)
API and identity API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator
Containers and compute ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic
Data, analytics, and AI Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Redshift Serverless, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker
Databases and caching RDS, RDS Data API, Neptune, DocumentDB, DMS, MemoryDB, ElastiCache, Timestream for InfluxDB
Messaging and transfer SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations
Security and governance AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace
Cost and billing AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Pricing Calculator, BCM Data Exports
Resilience, backup, and config AWS FIS, AWS Backup, Amazon Data Lifecycle Manager, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API

For operation-level compatibility, see the Services Overview.

Detailed service notes
Service How it works Notable features
SSM In-process + EC2 containers Parameter Store (version history, labels, SecureString, tagging); Run Command (SendCommand, GetCommandInvocation, direct EC2 container execution, agent polling)
SQS In-process Standard and FIFO queues, DLQ, visibility timeout, batch operations, tagging
SNS In-process Topics, subscriptions, SQS, Lambda and HTTP delivery, tagging
S3 In-process Versioning, multipart upload, pre-signed URLs, Object Lock, object annotations, event notifications
S3 Vectors In-process Vector buckets, indexes, put / get / list / delete vectors, cosine similarity queries
DynamoDB In-process GSI, LSI, Query, Scan, TTL, transactions, batch operations; Streams with shard iterators and Lambda event source mapping
Lambda Real Docker Runtime environment, execution model, warm container pool, aliases, Function URLs
API Gateway REST In-process Resources, methods, stages, Lambda proxy, MOCK integrations, AWS integrations
API Gateway v2 In-process HTTP APIs, routes, integrations, JWT authorizers, stages
AppSync In-process GraphQL API management API, schema registry, AWS scalars, domain names, channel namespaces
IAM In-process Users, roles, groups, policies, instance profiles, access keys; STS AssumeRole, WebIdentity, SAML, GetFederationToken, GetSessionToken
Cognito In-process User pools, app clients, auth flows, JWKS and OpenID well-known endpoints
KMS In-process Encrypt, decrypt, sign, verify, data keys, aliases
Kinesis In-process Streams, shards, enhanced fan-out, split and merge
Secrets Manager In-process Versioning, resource policies, tagging
Step Functions In-process ASL execution, task tokens, execution history
SWF In-process Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation
CloudFormation In-process Stacks, change sets, resource provisioning, StackSets (cross-account instances)
EventBridge In-process Custom buses, rules, SQS, SNS and Lambda targets
EventBridge Pipes In-process Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering
EventBridge Scheduler In-process Schedule groups, schedules, flexible time windows, retry policies, DLQs
CloudWatch Logs In-process Log groups, streams, ingestion, filtering
CloudWatch Metrics In-process Custom metrics, statistics, alarms
CloudWatch OAM In-process Full 15-operation sink, policy, cross-account link, and tagging API
ElastiCache Real Docker Redis / Valkey protocol, IAM auth, SigV4 validation
MemoryDB Real Docker Redis / Valkey protocol via real containers; JSON 1.1 control plane; reuses ElastiCache RESP proxy
RDS Real Docker PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines
Timestream for InfluxDB Real Docker, mock mode available InfluxDB 2.x DB instances and read replica clusters via influxdb:2.7; initial auth secret in Secrets Manager; backups and restore through the influx CLI
RDS Data API REST JSON over real RDS containers Raw SQL execution and transactions for local MySQL / MariaDB RDS resources
Neptune Real Docker Graph DB via TinkerPop Gremlin Server (default) or Neo4j for openCypher/Bolt (NEPTUNE_DB_TYPE); RDS-shaped control plane; SigV4 proxy on port 8182
DocumentDB Real Docker, mock mode available MongoDB-compatible cluster via real MongoDB containers; RDS-shaped control plane; MongoDB wire protocol on port 27017
MSK Real Docker Kafka-compatible broker via Redpanda
Amazon MQ Real Docker RabbitMQ broker via rabbitmq:3-management; AMQP + management console
Athena In-process with DuckDB sidecar Real SQL execution over S3 and Glue-backed views
Glue In-process Data Catalog, Schema Registry, tables consumed by Athena
EMR In-process Cluster (job flow) lifecycle, instance groups and fleets, steps, security configurations, tagging
Data Firehose In-process Streaming delivery, buffered flush to S3 with GZIP/ZIP/Snappy compression
Managed Service for Apache Flink Real Docker Kinesis Analytics V2 control plane; StartApplication runs a real Flink cluster (JobManager + TaskManager, image per RuntimeEnvironment), pulls the application JAR from local S3, and submits the job
ECS Real Docker Clusters, task definitions, tasks, services, capacity providers, task sets
EC2 Real Docker RunInstances launches containers, SSH key injection, UserData, IMDS, VPC resources
Lightsail In-process Instances, disks, static IPs, key pairs, ports, tags, regions, blueprints, bundles, operations
ACM In-process Certificate issuance and validation lifecycle
ECR In-process with real registry Repositories, docker push / pull, image-backed Lambda functions
Resource Groups Tagging API In-process GetResources, tag and untag resources, tag key and value discovery across services
SES In-process v1 and v2 APIs: send email, raw email, identity verification, DKIM, templates, configuration sets, account sending
OpenSearch Real Docker Domain CRUD, tags, versions, instance types, upgrade stubs
AppConfig In-process Applications, environments, profiles, hosted versions, deployments
AppConfigData In-process Configuration sessions and dynamic configuration retrieval
Bedrock In-process Guardrail lifecycle, versions, and tags on the control plane
Bedrock Runtime In-process stub Dummy Converse and InvokeModel responses for local development
Bedrock AgentCore In-process stub Stateful control plane (agent runtimes, gateways, memory, workload identity); canned InvokeAgentRuntime responses
EKS Real Docker, mock mode available k3s clusters with live Kubernetes API server
MWAA Real Docker, mock mode available Real Apache Airflow (LocalExecutor) + Postgres metadata DB per environment; web/CLI proxy; S3-backed DAG sync
ELB v2 In-process ALB, NLB, target groups, listeners, routing rules, Lambda targets, tags
CodeBuild In-process with real Docker Real buildspec execution, CloudWatch logs, S3 artifacts
CodeDeploy In-process with Lambda traffic shifting Deployment groups, configs, lifecycle hooks, auto-rollback
CodePipeline In-process orchestration Pipelines, executions, S3 artifacts, approvals, local providers, custom workers
AWS Network Firewall In-process DescribeFirewall with stable emulated endpoint attachments for infrastructure tooling
Service Quotas In-process Generated quota catalog with generous static values; real quota codes for CodeBuild and Lambda concurrency
AWS RAM In-process EnableSharingWithAwsOrganization opt-in
AWS Batch In-process Compute environments, job queues, job definitions, job submission and lifecycle
Auto Scaling In-process with reconciler Launch configs, ASGs, desired capacity reconciliation, lifecycle hooks
Application Auto Scaling In-process Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert)
Elastic Beanstalk In-process Applications, application versions, environments, configuration templates, platform and solution stack metadata
AWS Backup In-process Vaults, backup plans, selections, simulated job lifecycle, recovery points
Amazon Data Lifecycle Manager In-process Lifecycle policy and tag management; schedules are stored but do not create snapshots or AMIs
AWS FIS In-process All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services
AWS Config In-process Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging
Organizations In-process Organizations, roots, nested OUs, member accounts, all policy types with FullAWSAccess and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to
CloudTrail In-process Trails, event selectors (S3 data events with bucket/prefix matching), StartLogging/StopLogging, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits AccessDenied records
CloudFront In-process Distributions, origins, cache behaviors, invalidations, tagging
WAF v2 In-process Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes)
Resource Explorer 2 In-process All 32 management APIs: index and view lifecycle, multi-Region setup tasks, the full search query grammar, and tagging; 30 services expose their resources for search, gathered live rather than from an index
Route53 In-process Hosted zones, SOA and NS records, resource record sets, change tracking, tagging
Cloud Map In-process HTTP and DNS namespaces, services, instance registration, discovery queries, operations, tagging
Transfer Family In-process Server lifecycle, user management, SSH key import, tagging
Textract In-process stub API-compatible stubs, dummy block data, async job simulation
Transcribe In-process stub Transcription jobs and custom vocabularies; jobs complete immediately, no real audio processing
Pricing In-process with static snapshot Product discovery, attributes, price list files, pagination
Cost Explorer In-process Cost synthesized from Floci resource state and pricing snapshots
Cost and Usage Reports In-process with floci-duck sidecar CUR 2.0 and FOCUS 1.2 columns, account-scoped storage, Parquet emission
BCM Pricing Calculator In-process Workload estimate create, usage pricing, read, and delete lifecycle
BCM Data Exports In-process Export lifecycle, executions, update and delete operations

Real Docker Integration

Floci uses real Docker containers when in-process emulation would reduce fidelity. This applies to stateful databases, connection-heavy protocols, runtimes, and build systems.

Service Default image What is real
Lambda public.ecr.aws/lambda/<runtime> AWS runtime environment, execution model, warm container pool
ElastiCache valkey/valkey:8 Redis / Valkey protocol, ACL-based IAM auth, SigV4 validation
RDS PostgreSQL postgres:16-alpine PostgreSQL engine, IAM auth, JDBC-compatible access
RDS MySQL / Aurora mysql:8.0 MySQL engine, IAM auth, JDBC-compatible access
RDS MariaDB mariadb:11 MariaDB engine, IAM auth, JDBC-compatible access
Neptune tinkerpop/gremlin-server:3.7.3 TinkerPop Gremlin Server; Gremlin WebSocket on port 8182; SigV4 auth proxy
Neptune (openCypher) neo4j:5-community Neo4j backend when FLOCI_SERVICES_NEPTUNE_DB_TYPE=neo4j; openCypher over Bolt
DocumentDB mongo:7.0 MongoDB engine; MongoDB wire protocol on port 27017
MSK redpandadata/redpanda:latest Kafka-compatible broker via Redpanda
Amazon MQ rabbitmq:3-management RabbitMQ broker; AMQP on port 5672, management console on 15672
Managed Service for Apache Flink apache/flink:<version> Apache Flink JobManager; image chosen per RuntimeEnvironment (FLINK-1_15 … FLINK-1_20, FLINK-2_0 … FLINK-2_3)
EC2 AMI-mapped Linux images Linux containers, SSH key injection, UserData, IMDS, IAM credentials
ECS User-specified task image Container lifecycle, start, stop, health checks
EKS rancher/k3s:latest Kubernetes API server via k3s
MWAA apache/airflow:<version>-python3.12 + postgres:16-alpine Real Apache Airflow (LocalExecutor: scheduler + webserver) with its own Postgres metadata DB; webserver/CLI reachable via Floci's proxy
CodeBuild User-specified environment image Buildspec execution, log streaming, S3 artifact upload
OpenSearch opensearchproject/opensearch:2 Full OpenSearch engine with REST API
ECR registry:2 OCI-compatible registry for docker push and docker pull
Verified Permissions floci/floci-sidecar-cedar:1.1.0 Cedar 4 policy parsing, schema validation and authorization decisions, via a Floci sidecar
AppSync floci/floci-sidecar-graphql:0.2.0 graphql-java schema validation, query planning and execution, via a Floci sidecar

Docker-backed services require the Docker socket:

docker run -d --name floci \
  -p 4566:4566 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -u root \
  floci/floci:latest

Overriding default images

Variable Default
FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE valkey/valkey:8
FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE postgres:16-alpine
FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE mysql:8.0
FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE mariadb:11
FLOCI_SERVICES_MSK_DEFAULT_IMAGE redpandadata/redpanda:latest
FLOCI_SERVICES_OPENSEARCH_DEFAULT_IMAGE (unset — images resolve per requested EngineVersion)
FLOCI_SERVICES_KINESIS_ANALYTICS_DEFAULT_IMAGE (unset; chosen per RuntimeEnvironment)
FLOCI_SERVICES_NEPTUNE_DEFAULT_IMAGE tinkerpop/gremlin-server:3.7.3
FLOCI_SERVICES_NEPTUNE_DEFAULT_NEO4J_IMAGE neo4j:5-community
FLOCI_SERVICES_DOCDB_DEFAULT_IMAGE mongo:7.0
FLOCI_SERVICES_EKS_DEFAULT_IMAGE rancher/k3s:latest
FLOCI_SERVICES_MWAA_DEFAULT_POSTGRES_IMAGE postgres:16-alpine
FLOCI_SERVICES_ECR_REGISTRY_IMAGE registry:2
FLOCI_SERVICES_LAMBDA_ECR_BASE_URI public.ecr.aws

Persistence and Storage Modes

Floci can trade speed for durability depending on the workflow. Configure the default mode with FLOCI_STORAGE_MODE, or override storage per service.

Mode Behavior Best for Durability
memory Entirely in RAM. Data is lost when the container stops. CI and ephemeral tests None
persistent Loaded at startup and flushed to disk immediately on every write operation. Simple local state preservation with immediate persistence Medium
hybrid In-memory performance with periodic async flushing every 5 seconds. Local development Good
wal Write-ahead log. Every mutation is logged before responding. Maximum durability Highest

Use memory for fast test runs. Use hybrid when you want state preserved across container restarts without much overhead.

For more detail, see the Storage Configuration documentation.

Multi-Account Isolation

Floci supports per-account resource isolation with no extra setup. If AWS_ACCESS_KEY_ID is exactly 12 digits, Floci uses it as the account ID. Resources created by one account are invisible to another.

AWS_ACCESS_KEY_ID=111111111111 aws sqs create-queue --queue-name orders
AWS_ACCESS_KEY_ID=222222222222 aws sqs create-queue --queue-name orders

Any other key format, such as test or AKIA..., causes Floci to fall back to FLOCI_DEFAULT_ACCOUNT_ID, which defaults to 000000000000.

STS temporary credentials are routed too: credentials from AssumeRole resolve to the assumed role's account, so the cross-account assume-role-then-provision pattern works locally. Resolution precedence is 12-digit AKID → temporary-session lookup → FLOCI_DEFAULT_ACCOUNT_ID.

See the Multi-Account Isolation docs.

SDK Integration

Point your existing AWS SDK at http://localhost:4566.

Java, AWS SDK v2
var client = DynamoDbClient.builder()
    .endpointOverride(URI.create("http://localhost:4566"))
    .region(Region.US_EAST_1)
    .credentialsProvider(StaticCredentialsProvider.create(
        AwsBasicCredentials.create("test", "test")))
    .build();

client.createTable(b -> b
    .tableName("demo-table")
    .billingMode(BillingMode.PAY_PER_REQUEST)
    .attributeDefinitions(
        AttributeDefinition.builder().attributeName("pk").attributeType(ScalarAttributeType.S).build())
    .keySchema(
        KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build()));

System.out.println(client.listTables().tableNames());
Python, boto3
import boto3

client = boto3.client(
    "ssm",
    endpoint_url="http://localhost:4566",
    region_name="us-east-1",
    aws_access_key_id="test",
    aws_secret_access_key="test",
)

client.put_parameter(
    Name="/demo/app/message",
    Value="hello from floci",
    Type="String",
    Overwrite=True,
)

response = client.get_parameter(Name="/demo/app/message")
print(response["Parameter"]["Value"])
Node.js, AWS SDK v3
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";

const client = new SQSClient({
  endpoint: "http://localhost:4566",
  region: "us-east-1",
  credentials: { accessKeyId: "test", secretAccessKey: "test" },
});

await client.send(
  new SendMessageCommand({
    QueueUrl: "http://localhost:4566/000000000000/demo-queue",
    MessageBody: "hello from floci",
  }),
);
Go, AWS SDK v2
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/credentials"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    cfg, err := config.LoadDefaultConfig(context.TODO(),
        config.WithRegion("us-east-1"),
        config.WithCredentialsProvider(
            credentials.NewStaticCredentialsProvider("test", "test", ""),
        ),
        config.WithBaseEndpoint("http://localhost:4566"),
    )
    if err != nil {
        log.Fatal(err)
    }

    client := s3.NewFromConfig(cfg, func(o *s3.Options) {
        o.UsePathStyle = true
    })

    out, err := client.ListBuckets(context.TODO(), nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out.Buckets)
}
Rust, AWS SDK
use aws_sdk_secretsmanager::config::{Credentials, Region};
use aws_sdk_secretsmanager::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
        .region(Region::new("us-east-1"))
        .credentials_provider(Credentials::new("test", "test", None, None, "floci"))
        .endpoint_url("http://localhost:4566")
        .load()
        .await;

    let client = Client::new(&config);

    client
        .create_secret()
        .name("demo/secret")
        .secret_string("hello from floci")
        .send()
        .await?;

    Ok(())
}
Bash, AWS CLI
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
export AWS_DEFAULT_REGION=us-east-1

aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
aws --endpoint-url http://localhost:4566 s3 ls

Testcontainers

Floci has Testcontainers modules for starting isolated Floci instances directly from tests. This avoids shared state, manual daemon setup, and port conflicts.

For Testcontainers 1.x, use the versions as indicated in the table below.

Language Package Latest Registry Source
Java io.floci:testcontainers-floci 1.14.0 Maven Central GitHub
Node.js @floci/testcontainers 0.1.0 npm GitHub
Python testcontainers-floci 0.1.1 PyPI GitHub
.NET Testcontainers.Floci see releases GitHub Packages GitHub
Go In progress In progress N/A GitHub
Java
<dependency>
    <groupId>io.floci</groupId>
    <artifactId>testcontainers-floci</artifactId>
    <version>1.14.0</version>
    <scope>test</scope>
</dependency>
@Testcontainers
class S3IntegrationTest {

    @Container
    static FlociContainer floci = new FlociContainer();

    @Test
    void shouldCreateBucket() {
        S3Client s3 = S3Client.builder()
                .endpointOverride(URI.create(floci.getEndpoint()))
                .region(Region.of(floci.getRegion()))
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey())))
                .forcePathStyle(true)
                .build();

        s3.createBucket(b -> b.bucket("my-bucket"));
    }
}

For Testcontainers 2.x / Spring Boot 4.x, use version 2.15.0.

Node.js / TypeScript
npm install --save-dev @floci/testcontainers
import { FlociContainer } from "@floci/testcontainers";
import { S3Client, CreateBucketCommand } from "@aws-sdk/client-s3";

describe("S3", () => {
  let floci: FlociContainer;

  beforeAll(async () => {
    floci = await new FlociContainer().start();
  });

  afterAll(async () => {
    await floci.stop();
  });

  it("creates a bucket", async () => {
    const s3 = new S3Client({
      endpoint: floci.getEndpoint(),
      region: floci.getRegion(),
      credentials: {
        accessKeyId: floci.getAccessKey(),
        secretAccessKey: floci.getSecretKey(),
      },
      forcePathStyle: true,
    });

    await s3.send(new CreateBucketCommand({ Bucket: "my-bucket" }));
  });
});
Python
pip install testcontainers-floci
import boto3
from floci import FlociContainer


def test_s3_create_bucket():
    with FlociContainer() as floci:
        s3 = boto3.client(
            "s3",
            endpoint_url=floci.get_endpoint(),
            region_name=floci.get_region(),
            aws_access_key_id=floci.get_access_key(),
            aws_secret_access_key=floci.get_secret_key(),
        )
        s3.create_bucket(Bucket="my-bucket")

Compatibility Testing

The compatibility-tests directory validates Floci across SDKs and tooling workflows.

Module Language / Tool SDK / Client Tests
sdk-test-java Java 17 AWS SDK for Java v2 1,326
sdk-test-node Node.js AWS SDK for JavaScript v3 449
sdk-test-python Python 3 boto3 311
sdk-test-go Go AWS SDK for Go v2 + RDS Data API SDK v1 157
sdk-test-awscli Bash AWS CLI v2 205
compat-terraform Terraform v1.10+ 67
compat-opentofu OpenTofu v1.9+ 41
compat-cdk AWS CDK v2+ 20

2,576 automated compatibility tests across 5 SDKs and 3 IaC tools.

Migrating from LocalStack

Floci is a drop-in replacement for LocalStack Community. The port, credentials, SDK configuration, and CLI endpoint pattern work the same way. Swap the image and keep going.

# Before
image: localstack/localstack

# After, standard image
image: floci/floci:latest

# After, if init scripts need AWS CLI or boto3
image: floci/floci:latest-compat

LocalStack environment variables are translated automatically:

LocalStack Floci equivalent
LOCALSTACK_HOST FLOCI_HOSTNAME
PERSISTENCE=1 FLOCI_STORAGE_MODE=persistent
LAMBDA_DOCKER_NETWORK FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK
LAMBDA_REMOVE_CONTAINERS=1 FLOCI_SERVICES_LAMBDA_EPHEMERAL=true
DEBUG=1 QUARKUS_LOG_LEVEL=DEBUG

Init scripts mounted under /etc/localstack/init/ run unchanged. The /_localstack/init and /_localstack/health endpoints are still served. Once the emulator is up, the log also ends with a LocalStack-style Ready. line, so tooling that watches the log for it, such as the default wait strategy of Testcontainers' LocalStackContainer, works unchanged. Set LOCALSTACK_PARITY=false to opt out of automatic translation.

See the full migration guide.

Image Tags

Every tag combines a variant and a channel.

Channel Standard Baseline (ARM64 only) Compat with AWS CLI and boto3
Release, floating latest latest-baseline latest-compat
Release, pinned x.y.z x.y.z-baseline x.y.z-compat
Nightly, floating nightly — nightly-compat
Nightly, dated nightly-mmddyyyy — nightly-mmddyyyy-compat

Use latest for stable releases, a pinned version for reproducible builds, and nightly to track main.

# Recommended
image: floci/floci:latest

# Includes AWS CLI and boto3
image: floci/floci:latest-compat

# ARM64 baseline for Raspberry Pi 4 / pre-LSE cores
image: floci/floci:latest-baseline

# Pinned release
image: floci/floci:x.y.z

# Track main
image: floci/floci:nightly

Release train

Stable releases ship on the 1st and 3rd Tuesday of each month. Between trains, floci/floci:nightly tracks main. Every merged fix is available the next day, and dated nightly-mmddyyyy tags let you pin a specific night's build.

Versions are derived from Conventional Commits by semantic-release; CHANGELOG.md is generated, never hand-edited. Releases are cut from main only: there are no maintenance branches.

Configuration

All settings are overridable through environment variables with the FLOCI_ prefix.

Variable Default Description
FLOCI_PORT 4566 Port exposed by the Floci API
FLOCI_DEFAULT_REGION us-east-1 Default AWS region
FLOCI_DEFAULT_ACCOUNT_ID 000000000000 Default AWS account ID
FLOCI_BASE_URL http://localhost:4566 Base URL used when Floci returns service URLs
FLOCI_HOSTNAME Unset Hostname used in returned URLs when Floci runs inside Docker Compose
FLOCI_STORAGE_MODE memory Storage mode: memory, persistent, hybrid, or wal
FLOCI_STORAGE_PERSISTENT_PATH ./data Directory used for persisted state
FLOCI_SERVICES_LAMBDA_ECR_BASE_URI public.ecr.aws ECR base URI used when pulling Lambda runtime images (legacy name FLOCI_ECR_BASE_URI still works)
FLOCI_SERVICES_S3_ENFORCE_AUTH false Enforce S3 public/private read access and reject unknown signed S3 access keys

Full reference: configuration docs

Multi-container Docker Compose

When your application runs in a different container, set FLOCI_HOSTNAME to the Floci service name so returned URLs, such as SQS QueueUrl values, resolve correctly.

services:
  floci:
    image: floci/floci:latest
    ports:
      - "4566:4566"
    environment:
      - FLOCI_HOSTNAME=floci

  my-app:
    environment:
      - AWS_ENDPOINT_URL=http://floci:4566
    depends_on:
      - floci

Without this, services may return URLs using localhost, which points to the wrong container from the application container.

Community

Join the Floci community on Slack or GitHub Discussions. Feature ideas, compatibility questions, design tradeoffs, and rough proposals are welcome.

Sponsors

Floci is independent open source, funded by the people and companies who use it. Sponsorship buys gratitude and nothing else: every emulated service is free for everyone, forever, and no sponsor gets features, priority, or roadmap influence that the rest of the Flock does not.

🥇 Gold

Large logo with top placement in the emulator READMEs and on floci.io, plus a mention in release notes.

IceGuard · Softmax

🥈 Silver

Logo in the emulator READMEs and on floci.io, plus a mention in release notes.

Your logo here. Become a sponsor.

🥉 Community

Name in the emulator READMEs, a sponsor badge on GitHub, and our sincere thanks.

AutoScout24 · Nexxion AI

Every sponsor, including the Friends of the Flock who support Floci outside these tiers, is listed in THANKS.md.

Sponsor Floci

Star History

Star History Chart

Contributors

License

MIT. Use it however you want.

S
Description
Light, fluffy, and always free - The AWS Local Emulator alternative
Readme MIT
478 MiB
0 Stars 1 Watchers 0 Forks
Languages
Java 96.7%
Python 2.1%
Shell 0.4%
TypeScript 0.3%
Go 0.2%