English | 한국어
Covers the persistent store, restart recovery, monitoring, request timeouts, resource-leak avoidance, and the build/publish procedure you need to know when running Protean in production.
Module descriptors (the declarative metadata) are stored durably in ModuleStore. The backend is chosen via protean.module-store.backend.
protean.module-store.backend=filesystem (default when unset).
protean:
module-store:
backend: filesystem
dir: /var/lib/protean/modules # default: ${java.io.tmpdir}/protean-modules- Current state:
dir/<id>.json. Writes go to a temp file → atomic move to prevent partial writes (crash) — write-ahead durability. - Version history:
dir/<id>.history/<seq>.json(append-only snapshots, for audit/rollback). - Note: the default
diris underjava.io.tmpdir. In production you must change it to a persistent path that is not wiped on reboot.
protean.module-store.backend=jdbc. Compared to the filesystem, it offers better durability and queryability, plus the multi-instance benefit of several main instances sharing the same store.
protean:
module-store:
backend: jdbc- At startup (
@PostConstruct) it auto-creates the schema (CREATE TABLE IF NOT EXISTS):module(current state),module_version(append-only history). Thedescriptor_jsoncolumn type and theseqauto-increment key are chosen per vendor by the activeModuleStoreDialect(H2CLOB/ MySQLLONGTEXT/ PostgreSQLTEXT; H2·MySQLBIGINT AUTO_INCREMENT/ PostgreSQLBIGSERIAL). - Supported vendors: H2, MySQL, and PostgreSQL are built in. The dialect is auto-detected from the JDBC database product name, or set it explicitly with
protean.module-store.dialect(h2|mysql|postgresql). An unrecognized vendor fails fast at startup with a clear message — it does not silently fall back to H2 DDL. To support another vendor (e.g. Oracle), register aModuleStoreDialectbean; see 10. SPI Extension. - After creating the schema it runs a startup self-check (a rolled-back 128 KB probe) confirming the
descriptor_jsoncolumn holds large text without truncation and thatseqauto-increments — so a boundedVARCHARor a broken dialect surfaces at boot, not later on a large descriptor. - It uses the application's
JdbcTemplate(i.e. theDataSourcethe consumer configured) as-is. It does not inject a separate DataSource. - The upsert uses
UPDATE → (0 rows) → INSERTinstead of MERGE, for DB portability.
Both backends store the same ModuleDescriptor JSON but in different locations. On switching (backend or JDBC dialect/vendor), existing descriptors are not migrated automatically — protean.module-store.dialect is restart-scoped for the same reason. If you need zero downtime, move the existing store's descriptors to the new backend, or redeploy the ACTIVE modules onto the new backend.
ModuleReconciler (ApplicationRunner, @Profile("!worker")) calls ModulePlatform.reconcile() at startup to redeploy the modules from the store.
- Only ACTIVE is restored. Via
store.listActive(), only those withdesiredState=ACTIVEare redeployed in each module's isolation mode. PENDING_APPROVALmodules are not restored — this blocks the bypass of serving an unapproved module via a restart.- An individual module's restore failure is only logged and skipped (it does not block restoring other modules). Check the result via the
reconcile: {restored}/{total} modules restoredlog. - reconcile does not re-run the gates; it redeploys the stored descriptor (already passed at install time). If the store is empty, it is a no-op.
- With scopes (
worker.db.auto-provision): each restored module re-attaches to the scope named in its descriptor, and the scope's DB is (re)provisioned lazily on that first deploy. The scope registry (ScopeStore) is unioned with the startup seed and self-heals — a scope named in a persisted descriptor is honored even if its registry entry was lost.
Under worker.db.auto-provision, a scope (tenant / business-domain grouping) is the unit of DB provisioning and worker/container packing. Deployers only select a scope; the operator owns its lifecycle via the scope admin API (REST /platform/scopes, MCP protean.scope_*).
Registry (ScopeStore). Scope metadata — ScopeRecord(name, state, dialectId), never credentials — is persisted in a ScopeStore backed by the same module-store.backend (filesystem | jdbc), separate from the module store. The ScopeManager facade merges it with the worker.db.scopes seed so the known set survives restarts.
State machine.
| Action | Effect | Data | Reversible |
|---|---|---|---|
| create / open | scope becomes ACTIVE (deployable); DB provisioned lazily on first deploy | — | — |
| close | removed from the deployable allowlist; running modules keep serving | untouched | ↔ open |
| detach | undeploy the scope's modules + reclaim its workers/containers + drop only the DB login | retained | ↔ re-create + redeploy |
| destroy | DROP DATABASE/SCHEMA CASCADE + login |
lost | ✗ |
Data safety. detach is the default, data-safe teardown — it stops the scope but keeps the database and all data (re-creating the scope and redeploying re-provisions the login). destroy is irreversible and guarded: it is refused unless worker.db.allow-destroy=true (default false) and the caller echoes the scope name as confirmation, and it is audit-logged. Data deletion is a DBA-owned action, not a routine deploy-path operation. Undeploy never tears down a scope (there is no deprovision-on-undeploy flag — teardown is only via detach/destroy above).
An in-memory trace ring buffer (TraceStore) is provided for runtime observation.
protean:
trace:
enabled: true # default true
capacity: 200 # default 200 — the most recent N requests (oldest discarded on overflow)RequestTraceFilteris the outermost (highest-priority) filter; it records every request's entry-to-response duration, status, and exceptions, and attributes it to the dynamic module by the matched handler pattern.- Query via
GET /platform/traces?limit=&moduleId=(→ 04. REST API Reference). - The ring buffer is bounded in-memory — it is lost on restart, and persistence/external exposure is a separate task. If you need long-term retention or aggregation, collect it separately via logs/APM.
- capacity is a trade-off against memory use. Under heavy traffic the recent window gets shorter, so increase it as needed when diagnosis is the goal.
The trace feature is split across config, REST, and MCP. Below is a reference hub gathering the entire surface; see the linked docs for each detail. Trace recording is on by default (lightweight), and per-module aggregate metrics are opt-in (when off, the recording hot path is just a single boolean check).
Config (protean.trace.*) — detail 03. Configuration Reference
| Key | Default | Meaning |
|---|---|---|
enabled |
true |
Request trace recording on/off |
capacity |
200 |
Ring-buffer capacity (most recent N; oldest discarded on overflow) |
metrics.enabled |
false |
Per-module aggregate metrics (opt-in) |
metrics.latency-buckets |
20 |
Number of latency histogram buckets (precision ↔ memory) |
metrics.max-modules |
512 |
Max modules tracked (LRU eviction on overflow) |
Query surface — REST detail 04. REST API Reference, MCP detail 08. MCP Integration
| Kind | Endpoint / tool | Returns | Filters |
|---|---|---|---|
| REST | GET /platform/traces |
RequestTrace[] |
limit (default 50, min 1) · moduleId · errorsOnly · status · minLatencyMs · since · beforeSeq (AND, newest-first) |
| REST | GET /platform/traces/metrics |
ModuleMetricsSnapshot[] |
moduleId (all modules if omitted); empty list if metrics off |
| MCP tool | protean.query_traces |
{enabled, traces[]} |
same filters as above |
| MCP tool | protean.module_metrics |
{enabled, metrics[]} |
moduleId |
| MCP resource | protean://traces |
recent traces (fixed 50) | — |
Data model
RequestTrace(one request):seq·epochMillis·method·uri·pattern(nullif unmatched) ·moduleId(nullfor platform/static) ·status·latencyMs·error(exception FQCN,nullif none) ·traceId(the correlation id shared with logs and RFC 9457 errors).ModuleMetricsSnapshot(module aggregate):moduleId("(platform)"for platform) ·count·errorCount(exception or status ≥ 500) ·errorRate·p50/p95/p99LatencyMs·maxLatencyMs·lastSeenEpochMillis.
Recording pipeline (internal)
| Component | Role |
|---|---|
RequestTraceFilter |
Highest-priority filter; records entry-to-response duration, status, exceptions; attributes to a module by handler pattern |
CorrelationIdFilter |
Assigns the X-Request-Id/MDC traceId correlation id → links trace, logs, and error responses |
TraceStore |
Bounded ring buffer; its own query path (/platform/traces) is not recorded |
TraceMetrics / LatencyHistogram |
When metrics are opt-in, aggregates per-module counters and a log-linear latency histogram |
Attribution scope per isolation mode (worth knowing)
The meaning of the latency recorded by the main platform's traces/metrics differs by isolation mode.
- in-process — the handler runs directly in the main JVM, so the trace's
latencyMs= the module's execution time as-is. - worker / container — the request is forwarded to the worker/container by the reverse proxy. The main's trace/metrics attribute it to that module accurately (
moduleIdis filled in), but the recorded latency is the proxy-hop (= client-perceived) latency (including the network round-trip). The module's internal execution time and the worker's own detailed trace live in theTraceStoreinside that worker/container JVM, and because the worker does not expose/platform/traces(due to@Profile("!worker")), it is not queried directly from the main. Collect it via the worker's logs/APM if needed.
Whether to expose the internal-execution observability of worker/container modules through a single window (aggregate pull-back / console multi-source) is subject to a support-feasibility determination — see ROADMAP.
ModuleExecutionWatchdog puts a deadline on module request execution.
protean:
module:
request-timeout-ms: 0 # default 0 = unlimited- Cooperative limit: on deadline exceed, it
interrupts the execution thread. It breaks blocking such asThread.sleepand interruptible I/O, but a CPU spin (while(true){}) ignores the interrupt and cannot be stopped. - A hard cap (runaway CPU/memory) is the job of OS/process isolation (worker/container mode). In in-process mode the timeout is only a line of defense, not hard isolation.
A dynamic module is loaded under its own ModuleClassLoader. If that ClassLoader is not GC'd after unload, Metaspace is not reclaimed and you eventually hit a Metaspace OOM. The platform and the module must both uphold this.
- What the platform does: on
unregister/swap,DynamicEndpointRegistrarnot only releases the mapping but also evicts, keyed by the controller Class, the per-Class caches of the MVC infrastructure that were populated by calls (RequestMappingHandlerAdapter'ssessionAttributesHandlerCache·initBinderCache·modelAttributeCache, the argument-resolver caches,ExceptionHandlerExceptionResolvercaches, and the registered@ControllerAdvicecaches). Releasing only the mapping would let a cache pin the ClassLoader and cause a hard leak. - What the module must do:
- Inject the managed executor
ProteanTaskExecutor(per-module · daemon · bounded) to run async/scheduled work. Using this instead of a rawnew Threadmeans that on unload, closing the child context triggersclose()(→shutdownNow) so threads and jobs are cleaned up. It prevents leaks of shared threads that pin a dead ClassLoader. - Clean up out-of-context resources that the child context cannot reach (ThreadLocals on shared threads, static cache registrations, JMX MBeans, custom clients) yourself via a
ModuleUnloadCallbackbean. The platform invokes it just before closing the child context.
- Inject the managed executor
This project is built with Gradle. It calls gradle tasks directly rather than running via IDE integration.
Three jars come out in build/libs, plus a worker container image built by Jib.
- plain jar (no classifier,
protean-<ver>.jar): the ordinary library layout that other projects depend on (noBOOT-INF). The artifact consumers depend on. - bootJar (
-bootclassifier,protean-<ver>-boot.jar): the runnable fat jar (BOOT-INF/classes,lib) that the embed worker explodes and uses. Because there are twomain()s,springBoot.mainClassis fixed toProteanApplication. - worker jar (
-workerclassifier,protean-<ver>-worker.jar): a flat shaded uber-jar (Shadow) for the sidecar worker runtime's process track. That track launches with a barejava -cp, which a-boot.jar's nestedBOOT-INFlayout cannot satisfy — hence a flat jar. Spring auto-configuration imports and JDBC driver service files are concatenated during shading so the worker context still comes up. - worker image (
ghcr.io/<owner>/protean-worker:<ver>, built by Jib — nobuild/libsfile): the sidecar worker runtime's container track. Bundles the worker jar at/app/on a JDK base image (the worker recompiles module sources at runtime, so it needsjavac). See 05. Isolation Modes.
The test task limits the heap to maxHeapSize=512m to forcibly clear soft references in the leak canary. Bundling bootJar (fat-jar assembly, memory pressure) and test in one gradle invocation can make LeakDiagnosisTest and others throw a collateral OOM. Always invoke them separately.
Two invocations, and the order matters: the container and OS-isolation tests mount the fat -boot.jar, so they self-skip when it is absent (assumeTrue(bootJarExists()) in OsIsolationTest). clean deletes it. Run clean test first and 16 tests skip silently — the run is still green, but green over 580 tests rather than 596, and nothing in the output says so.
# Bad — combining risks OOM
./gradlew clean bootJar test
# Bad — separated, but `clean` removed the -boot.jar, so 16 container/isolation
# tests self-skip and the green is narrower than it looks
./gradlew clean test
./gradlew bootJar
# Good — separated, and the jar exists by the time the tests need it
./gradlew clean bootJar
./gradlew testOne consequence of putting everything in one local invocation: it is heavier than CI's split, because the container tests run Docker alongside the rest. Worker-spawn health checks (WorkerProcessIsolation.waitHealthy) can time out under that load and fail a test that passes on its own — observed once in two full runs while writing this section. Local maxRetries is 0 on purpose so flakiness stays visible, so re-run the class by itself (./gradlew test --tests 'org.htcom.protean.WorkerPoolTest') before treating such a failure as real.
CI does this differently on purpose, and that difference is not a bug to fix: its test job runs without a bootJar so the container tests self-skip there, and a dedicated isolation-test job builds the jar and then runs exactly those tests (.github/workflows/ci.yml). Splitting them keeps the two gates independently diagnosable and lets them run in parallel. Locally there is no such split, so a local pre-push check must put the jar first or it does not exercise those 16 tests at all.
./gradlew publishToMavenLocal # publish to ~/.m2 (for POM / consumability verification)- The publication comprises
components.java(plain jar + the worker shaded jar the Shadow plugin contributes, distinguished by theshadowedbundling attribute so default consumers still resolve the plain jar) + sources jar + javadoc jar + the generated POM. - The worker container image publishes separately via Jib:
./gradlew jibpushesghcr.io/<owner>/protean-worker:<ver>whenGITHUB_OWNER/GITHUB_ACTOR/GITHUB_TOKENare set (otherwisejibDockerBuild/jibBuildTarbuild it locally). CI runs this on pushes tomainonly, gated exactly like the library publish. - The JDBC drivers (
mysql-connector-j,postgresql) are needed for protean's own bootJar/tests but are markedoptional=truein the published POM so as not to force them transitively on consumers. A consumer using worker DB provisioning must add its own driver explicitly. - Releases go to Maven Central (Sonatype Central Portal) via the
com.vanniktech.maven.publish.baseplugin. The release coordinate is never committed — the release is injected with-Pversion=<release>. What is committed is the next version as a SNAPSHOT (0.1.0-SNAPSHOTwhile 0.1.0 is being worked towards), bumped right after each release: the SSEreadyframe reports this value to clients asplatformVersion, and a default left at the version just released would make every development build announce itself as older than a release it already surpassed (0.0.1-SNAPSHOTsorts before0.0.1).publishToMavenCentralfirst runs theverifyReleaseArtifactgate (artifact set + a real consume test), then uploads; the deployment stops at VALIDATED and going live is a separate manual Publish on the Portal. Signing is in-memory and property-gated (signingInMemoryKey*), so a build without the key still publishes unsigned elsewhere. The upload is driven by the manualReleaseworkflow (workflow_dispatch), never by a tag push. - GitHub Packages carries the development snapshots (CI publishes on pushes to
main). The URL/credentials are not hardcoded inbuild.gradlebut externalized viagradle.properties/environment variables. The remote repository is registered only when all ofgithubOwner/githubRepo/githubActor/githubToken(or theGITHUB_OWNER/GITHUB_REPO/GITHUB_ACTOR/GITHUB_TOKENenv vars) are provided (otherwise mavenLocal only), and it is then published via thepublishLibraryPublicationToGitHubPackagesRepositorytask. For the credential template seegradle.properties.example.