Storage backend
Floci's storage backend gives each emulated service one way to retain resource state. It separates account isolation and service-defined region identity from the choice of in-memory or persistent storage. File-backed services restore state after restart. Container-backed services keep data in Docker volumes and use the storage layer for resource metadata.
Storage model
Service-facing storage
The service-facing storage contract gives resource handlers one way to create, read, list, replace, and delete state. A factory selects the backing mode. An account-aware view then hides account partitioning from service code.
The contract also supports grouped writes and deletes. A backend publishes a grouped change as one result or rejects it without a partial result. A scan returns a separate list so callers can use the result without changing the store. StorageOperations keeps value-based deletion atomic and preserves legacy-key ownership when the store is account-aware.
StorageBackedMap provides a map-shaped view for services whose control-plane state uses string keys. It preserves that service API while routing changes through the selected backend.
References: src/…/StorageBackend.java• L15-68 src/…/StorageFactory.java• L25-48 src/…/StorageBackedMap.java• L20-55 src/…/StorageOperations.java• L11-31
Account and region scope
The account-aware view chooses the account from the current request context. Startup and background work use the configured default account when no request context exists. It stores account-relative keys under an account prefix, then hides that prefix from normal service operations.
The storage layer does not add a region prefix. A service that needs account and region scope places the region in its logical key or resource identity. This lets each service keep its own rules for regional resources and global names.
Background work that updates a known resource uses explicit account access. Cross-account lookup can return the owning account, so the caller updates the original partition instead of creating a second copy. Older keys move only when the resource value proves ownership of the destination account and scope. Legacy keys are written to their scoped destination before the old key is removed, and an existing destination is preserved rather than overwritten.
This diagram shows how request scope, explicit owner scope, and legacy migration keep resource state in the correct account and region.
flowchart LR
Request[Request] --> View[Account-aware view]
View --> Partition[Account partition]
View --> Region[Service region identity]
Worker[Background work] --> Owner[Explicit owner account]
Legacy[Legacy state] --> Check[Ownership check]
Check -->|valid| Move[Move to scoped key]
Check -->|not valid| Keep[Keep state and fail closed]
References: src/…/AccountAwareStorageBackend.java• L24-39 src/…/AccountAwareStorageBackend.java• L208-332 src/…/AccountAwareStorageBackend.java• L420-525 src/…/AccountAwareStorageBackend.java• L679-743 src/…/AccountAwareStorageBackend.java• L775-824
Storage modes
In-memory state
In-memory storage keeps resource state in the process. Load and flush are no-ops. It supports grouped changes for all-or-nothing updates, but all state ends when the process stops.
References: src/…/InMemoryStorage.java• L11-15 src/…/InMemoryStorage.java• L19-85
Persistent snapshots
Persistent storage keeps a live in-memory view and writes a complete JSON snapshot when state changes. File replacement is atomic, so a reader sees the old snapshot or the new snapshot rather than a partial file. An unreadable snapshot is moved aside and reported; the store then starts empty instead of silently treating damaged state as valid.
References: src/…/PersistentStorage.java• L22-40 src/…/PersistentStorage.java• L42-71 src/…/PersistentStorage.java• L118-154 src/…/StorageQuarantine.java• L10-31
Scheduled persistence
Hybrid storage applies changes to memory at once and writes a full JSON snapshot on a schedule. A clean shutdown performs the final flush. A process failure can lose changes made after the last successful flush, so this mode trades a bounded loss window for lower write cost. A failed flush keeps the store dirty so a later flush can retry it.
References: src/…/HybridStorage.java• L22-44 src/…/HybridStorage.java• L46-79 src/…/HybridStorage.java• L101-148
Journaled persistence
WAL storage, where WAL means write-ahead log, serves reads from memory and appends changes to a durable log. Periodic compaction folds the log into a JSON snapshot. Startup loads the snapshot and replays later records, so frequent changes do not need a full snapshot for every request.
The log protects grouped changes as one record. Each record has a length boundary, so replay can keep earlier valid records and cut an unreadable tail after a crash. If a write cannot be rolled back with certainty, later writes stop until the log is repaired or replaced.
Append-heavy data can select this behavior through WriteProfile when the configured service mode is persistent. The profile changes the write path without changing the service-facing contract.
References: src/…/WalStorage.java• L37-51 src/…/WalStorage.java• L99-175 src/…/WalStorage.java• L214-241 src/…/WalStorage.java• L300-323 src/…/WalStorage.java• L325-426 src/…/WalStorage.java• L464-568 src/…/WriteProfile.java• L3-19
Partitioned map state
Partitioned storage serves values that are maps, such as a resource with many independently changing entries. It spreads one logical value across shard files, so a small entry change does not rewrite the full value. The same data can use immediate writes, scheduled writes, or an entry journal based on the selected mode.
Services use entry-level writes only when the selected backend supports MapEntryWriter. Whole-value reads and replacements remain available, which keeps the service model independent of the physical layout.
References: src/…/PartitionedFileStorage.java• L41-67 src/…/PartitionedFileStorage.java• L71-93 src/…/PartitionedFileStorage.java• L201-274 src/…/MapEntryWriter.java• L3-16 src/…/AccountAwareStorageBackend.java• L591-621
Serialization boundaries
Snapshot representation
JSON is the boundary between live resource models and file-backed snapshots. Full-file and scheduled stores write one map to one file. Partitioned stores write JSON objects that identify the logical key and hold one shard's entries. The factory supplies the value type needed to rebuild service models during load.
Atomic file replacement keeps a failed write from becoming a partial snapshot. When a snapshot cannot be read, quarantine preserves the file for diagnosis and makes the loss visible.
References: src/…/PersistentStorage.java• L31-40 src/…/HybridStorage.java• L30-43 src/…/PartitionedFileStorage.java• L686-699 src/…/StorageFactory.java• L59-88 src/…/StorageQuarantine.java• L20-31
JSON record boundary
StorageJson defines the shared record form used by file snapshots and by the mapper that backs the journal. It keeps Java time values as ISO-8601 text rather than numeric timestamps. Its copy operation passes a record through that stored form, which gives callers a separate value with the same serialization behavior as a reload.
References: src/…/StorageJson.java• L8-40
Journal representation
Journal records use length-framed binary data. Jackson CBOR carries keys and values in WAL records, while the shared storage mapper keeps supported record types consistent with JSON snapshots. The partitioned entry journal records one map-entry change at a time. Replay applies complete readable records in order and stops at the first torn or invalid record.
References: src/…/WalStorage.java• L43-50 src/…/WalStorage.java• L429-468 src/…/StorageJson.java• L19-27 src/…/EntryJournal.java• L28-43 src/…/EntryJournal.java• L117-177
Legacy state migration
Partitioned storage can recover an older single-file store or a snapshot-plus-log store when its new directory has no data. It writes recovered state to a staging directory, moves the complete directory into place, and marks the old files as migrated. This changes the physical layout without changing the resource state seen by services.
Account-aware migration follows the same safety rule for logical keys. It writes a valid destination before removing the source and preserves conflicting or unowned values for later recovery.
References: src/…/PartitionedFileStorage.java• L275-337 src/…/PartitionedFileStorage.java• L778-840 src/…/AccountAwareStorageBackend.java• L269-371 src/…/AccountAwareStorageBackend.java• L442-525 src/…/StorageFactory.java• L210-256
Backend lifecycle
Backend selection
StorageFactory reads each service's storage mode and flush interval from service configuration. It creates one logical backend for each storage path, wraps it with account isolation, and loads it once. Reusing a path returns the existing live backend rather than creating a second in-memory view that could overwrite newer state.
Map-valued resources use the partitioned form for non-memory modes. An append-heavy persistent profile selects journaled writes, while memory mode remains a simple in-memory store.
References: src/…/StorageFactory.java• L59-149 src/…/StorageFactory.java• L151-207
Startup and shutdown
The factory owns load, flush, clear, and shutdown across the backends it creates. Shutdown flushes before it stops schedulers and closes journal writers. Boot validation checks that the configured persistent path is writable whenever an enabled service uses a non-memory mode, so storage errors appear before service requests begin.
flowchart TD
Config[Service storage settings] --> Factory[StorageFactory]
Factory --> Select[Select mode and path]
Select --> Wrap[Account-aware backend]
Wrap --> Load[Load once]
Load --> Service[Service retains resource state]
Service --> Flush[Flush or clear]
Flush --> Stop[Final flush and shutdown]
References: src/…/StorageFactory.java• L267-320 src/…/PersistentPathValidator.java• L15-63 src/…/StorageFiles.java• L39-61
Container-backed state
Resource containers and volumes
Some emulated services keep resource data in a Docker container or named volume rather than in the Java store. The container lifecycle manager connects the service record to that external state through create, start, network, volume, and cleanup operations. A named volume can survive container replacement, so a failed or moved container does not require the service to discard the resource data.
Resource deletion can use strict cleanup. In that mode the service keeps the resource record and retries when Docker cannot confirm that the container or volume is gone. Normal teardown can also close an associated log stream after the container stops or is removed. This separates log draining from resource retention.
Container creation recovers from a lost response only when a conflicting named container carries the unique marker for that create attempt. This prevents a concurrent or stale container from being adopted as the resource's state.
References: src/…/ContainerLifecycleManager.java• L315-363 src/…/ContainerLifecycleManager.java• L572-613 src/…/ContainerLifecycleManager.java• L657-731 src/…/ContainerLifecycleManager.java• L982-1014
Volume root state
Named volumes can need one-time root setup before a non-root workload can use them. The lifecycle manager creates and labels the volume, then uses a short-lived helper container to apply the requested owner and permissions. It records successful setup for the process and retries after a failed setup or a newly created volume.
Strict volume removal reports failure instead of treating an unconfirmed removal as success. Resource services can then retain their record and retry cleanup without losing the link to external state.
References: src/…/ContainerLifecycleManager.java• L765-979 src/…/ContainerLifecycleManager.java• L982-1014
Container resource identity
Container-backed resources carry service, resource, account, and region identity on the Docker objects that retain their state. Names and labels let startup recovery find the right workload and let cleanup avoid objects owned by another Floci process. Named-volume mode retains data by policy, while memory mode removes it because no restart retention is promised.
This identity is separate from the Java key prefix. The service record and the Docker object must agree on the account and region so a restarted service can reconnect to the correct external state.
References: src/…/ContainerStorageHelper.java• L19-27 src/…/ContainerStorageHelper.java• L46-60 src/…/ContainerStorageHelper.java• L226-243 src/…/ContainerStorageHelper.java• L302-390 src/…/ContainerSpec.java• L15-56
Per-resource sidecars
Per-key container pools give sidecar-backed resources one lazy container per resource key. The pool reuses a healthy sidecar, starts one when needed, and restarts an unhealthy one. Calls for the same key serialize, while different keys can start independently.
Teardown advances a pool generation. A container that finishes starting during reset is detected and stopped, which prevents an untracked sidecar from retaining state after service shutdown.
References: src/…/PerKeyContainerPool.java• L10-22 src/…/PerKeyContainerPool.java• L59-105 src/…/PerKeyContainerPool.java• L118-190
Container network and reachability
Retained containers must remain on Floci's expected Docker network to be reachable after restart. If a survivor is on another network, the service replaces the container while preserving its volume-backed data. Published-port containers join a named network after creation on Docker Desktop because creating them on that network can suppress port publishing. Other daemons create them on the named network when possible.
Container specifications carry the network, endpoint, mount, and label choices that the lifecycle manager applies. The builder resolves the service or global network before creation, while the specification rejects link-local settings that cannot work on a user-defined network.
Launched containers use one shared endpoint rule for calls back to Floci. Embedded DNS supplies the configured hostname when the container has Floci's resolver. Otherwise the endpoint uses the Docker host or a reachable container address. The port is the internal Floci listener rather than a host-facing mapped port. EKS pods that cannot use the embedded resolver use the same endpoint helper without embedded DNS.
Container logs can flow to the console and CloudWatch Logs. The log streamer reassembles Docker's multiplexed stdout and stderr frames into lines, supports account- and region-scoped log destinations, and can observe a new container without forwarding its output. It gives a closing stream a short drain period, then closes the reader and flushes any final partial line. Exec output uses a separate callback because docker logs only covers the container's main process.
Failure diagnostics can also read a bounded tail of the container's combined stdout and stderr. If Docker cannot provide that tail, the original startup or execution failure remains the reported error.
flowchart LR
Resource[Emulated resource] --> Container[Retained container]
Container --> Volume[Named volume]
Container --> Network[Service network]
Container --> Logs[Log stream]
Logs --> Console[Floci console]
Logs --> CloudWatch[CloudWatch Logs]
Container --> Endpoint[Floci-reachable endpoint]
Endpoint --> Service[Floci service APIs]
References: src/…/ContainerBuilder.java• L79-101 src/…/ContainerSpec.java• L95-103 src/…/ContainerLifecycleManager.java• L367-384 src/…/ContainerLifecycleManager.java• L488-509 src/…/ContainerLifecycleManager.java• L1640-1665 src/…/ContainerLifecycleManager.java• L1760-1814 src/…/ContainerLifecycleManager.java• L1833-1909 src/…/ContainerLogStreamer.java• L63-160 src/…/ContainerLogStreamer.java• L220-343 src/…/ContainerLogStreamer.java• L346-579 src/…/ContainerReachableEndpoint.java• L11-32 src/…/ContainerReachableEndpoint.java• L55-103 src/…/ContainerEngineDetector.java• L16-85 src/…/ContainerNetworks.java• L9-37
Container runtime compatibility
Container-backed state must run on the platform served by the container daemon. Platform resolution normalizes the daemon's operating system and architecture before image checks. Native builds use a reflection registration boundary for Docker models that cross the JSON client boundary.
References: src/…/DockerPlatform.java• L10-41 src/…/DockerJavaNativeSupport.java• L5-11 src/…/DockerJavaNativeSupport.java• L12-141
Change checklist
When these files or sections are changed, remember to consider these:
- If
StorageBackendchanges, update every backing mode, the account-aware wrapper, and the map adapter that depends on grouped or atomic writes. - If account-prefix or region-key rules change, update explicit-account access, owner lookup, and legacy migration as one contract.
- If account-aware deletion changes, keep
StorageOperationsand legacy-key handling aligned so value-based cleanup cannot cross account boundaries. - If a storage mode or write profile changes, update
StorageFactory, path validation, load-once behavior, and shutdown ordering. - If the shared
StorageJsonmapper changes, check JSON snapshots, CBOR journal records, Java time values, and storage copy behavior together. - If snapshot or journal formats change, preserve a migration or compatibility path for existing state before writing the new format.
- If snapshot quarantine changes, keep unreadable files recoverable and keep startup from silently presenting damaged state as valid.
- If partition or shard naming changes, rewrite current files before removing old files so stale shards cannot restore deleted state.
- If entry-level writes change, keep
MapEntryWriter, whole-value replacement, and the selected backend's capability aligned. - If a persistent path is shared, preserve one live backend per path; duplicate stores can overwrite each other's state.
- If scheduled flush or journal compaction changes, keep dirty state retryable and complete the final flush before scheduler or writer closure.
- If container or volume cleanup changes, keep strict deletion retryable until Docker confirms removal.
- If shared-volume initialization changes, keep volume recreation able to rerun root setup and keep partial owner settings invalid.
- If container creation recovery changes, keep the per-attempt marker distinct from service labels so concurrent creates cannot adopt each other's containers.
- If container or volume identity changes, keep service, resource, account, and region labels aligned with recovery and prune rules.
- If sidecar pool teardown changes, preserve per-key start/stop locking and the generation check for starts racing reset.
- If retained-container network or endpoint rules change, keep network replacement, named-volume retention, embedded DNS, TLS host names, and internal ports aligned.
- If log streaming changes, preserve frame reassembly, final-tail draining, account and region log destinations, and the separate exec-output path.
- If Docker daemon support or model types change, update Docker/Podman selection, platform matching, and native reflection registration together.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A memory store or a hybrid store loses the process before its next flush | Resource state is missing after restart | Use persistent or journaled storage when restart retention matters; shut down through the factory for a final flush |
| A snapshot cannot be decoded | The store starts empty and persisted state is at risk | Quarantine the unreadable file and make the loss visible |
| A journal ends with a torn record | Changes after the last valid record are not restored | Replay valid records, cut the bad tail, and block uncertain writes until recovery |
| Background work writes through the caller's account | One resource can fork into two account-owned copies | Use explicit owner-account access from cross-account lookup |
| A legacy value cannot prove account or region ownership | State can appear in the wrong scope | Migrate only after the ownership predicate passes |
| Two live backends share one persistent path | A stale flush can overwrite newer state | Reuse the path-cached backend in StorageFactory |
| A partitioned shard or journal write fails | The in-memory change and durable layout can diverge | Keep the shard dirty or the journal intact and retry on the next flush or compaction |
| A strict container or volume removal is not confirmed | The service reports deletion while external state remains | Propagate the failure and retain the resource for retry |
| Shared-volume root setup fails | A non-root workload cannot use the retained volume | Leave setup retryable and do not mark the volume initialized |
| A lost create response causes a name conflict | The service may leak a created container or adopt a foreign one | Adopt only a named container with the exact create-attempt marker |
| A sidecar starts while the pool is resetting | An untracked container can remain after teardown | Register before the generation check and stop a start from an old generation |
| A retained container is on the wrong network | The service cannot reach the retained container | Replace the container and keep its named volume |
| A log stream closes before Docker delivers its final frames | The last partial line or queued output is missing | Allow bounded drain time, then close the transport and flush the tail |
| An exec output stream is not drained | The process in the container can stall on a full pipe | Attach the exec callback and consume its frames even when console logging is disabled |
| A container uses an unreachable host-facing endpoint or wrong engine mapping | Callback or service traffic fails inside the container | Use ContainerReachableEndpoint and detect Docker or Podman from the daemon |
Key files
| File | Why to read it |
|---|---|
| src/…/StorageBackend.java | Common contract for resource state |
| src/…/AccountAwareStorageBackend.java | Account partitions, owner lookup, and legacy migration |
| src/…/StorageOperations.java | Atomic value-based cleanup across account-aware and plain stores |
| src/…/StorageFactory.java | Mode selection, path reuse, loading, and lifecycle |
| src/…/InMemoryStorage.java | In-memory state and grouped changes |
| src/…/PersistentStorage.java | Synchronous JSON snapshots |
| src/…/HybridStorage.java | Scheduled snapshot persistence |
| src/…/WalStorage.java | Snapshot and write-ahead log persistence |
| src/…/StorageJson.java | Shared JSON and CBOR record rules |
| src/…/StorageQuarantine.java | Handling for unreadable persisted snapshots |
| src/…/PartitionedFileStorage.java | Sharded map state and layout migration |
| src/…/EntryJournal.java | Entry-level journal boundary |
| src/…/StorageBackedMap.java | Map-shaped service view over storage |
| src/…/PersistentPathValidator.java | Boot-time persistence path checks |
| src/…/ContainerLifecycleManager.java | Container, volume, network, endpoint, log, and cleanup lifecycle |
| src/…/ContainerSpec.java | Immutable launch contract for retained containers |
| src/…/PerKeyContainerPool.java | Per-resource sidecar retention and teardown races |
| src/…/ContainerNetworks.java | Detection of retained containers that lost Floci's network |
| src/…/ContainerLogStreamer.java | Container log observation, reassembly, and CloudWatch forwarding |
| src/…/ContainerReachableEndpoint.java | Callback endpoint used inside launched containers |
| src/…/ContainerEngineDetector.java | Docker and Podman daemon selection |
| src/…/DockerPlatform.java | Daemon platform and image matching |
| src/…/DockerJavaNativeSupport.java | Native reflection boundary for Docker models |