Think from the response up, not the database down.
Get started at BuildMosaic.org Β· Documentation Β· Kotlin API
Mosaic is a Kotlin library for building backends one response at a time. A Tile is a reusable piece of work that can read request or application data and compose other Tiles. Mosaic's dynamic DAG scheduler uses Kotlin coroutines to execute that work as its dependencies are discovered, sharing repeated work within each request.
Find the latest stable Runtime and Analysis versions in the release reference. For upgrades from 0.7.0, read the Runtime migration notes.
- π― Response first β Start with what your endpoint returns.
- π§© Self-contained Tiles β Each piece knows how to get what it needs.
- β‘ Shared work β Independent branches can reuse the same result.
- πΊοΈ Architecture you can see β Turn composition code into dependency diagrams.
An order page needs a summary and shipping details. That's also how you write it:
val OrderPageTile by singleTile {
val summary = composeAsync(OrderSummaryTile)
val logistics = composeAsync(LogisticsTile)
OrderPage(summary.await(), logistics.await())
}composeAsync starts the work; await gets the result. Both branches can run
concurrently. Use compose when you need a result before continuing.
The endpoint stays small even when the data behind it doesn't. The summary Tile builds its own part of the response:
val OrderSummaryTile by singleTile {
val order = composeAsync(OrderTile)
val customer = composeAsync(CustomerTile)
val lineItems = composeAsync(LineItemsTile)
OrderSummary(order.await(), customer.await(), lineItems.await())
}LineItemsTile goes deeper, fetching products and prices. None of that wiring
spills into the page Tile. Follow the complete order example
or see how the composition works.
The page needs line items. So does the order total:
val OrderTotalTile by singleTile {
compose(LineItemsTile).sumOf { it.price.amount * it.quantity }
}
// In a suspending handler, using the same request Mosaic:
val page = mosaic.composeAsync(OrderPageTile)
val total = mosaic.composeAsync(OrderTotalTile)
println("${page.await().summary.order.id}: ${total.await()}")Both branches reach LineItemsTile, but it runs once in this Mosaic. They share
its in-flight work and result without coordinating with each other.
Reuse is scoped to the same Mosaic and Tile instance; a new Mosaic starts
fresh. More on caching and identity β
Have a bulk API? Put it behind a MultiTile:
val ProductsByIdTile by multiTile<String, Product> { ids ->
source<ProductService>().getProducts(ids.toList())
}
// In the same request Mosaic:
val first = mosaic.compose(ProductsByIdTile, listOf("product-1"))
val next = mosaic.compose(ProductsByIdTile, listOf("product-1", "product-2"))
// The second call only fetches product-2.The same MultiTile and equal keys share work within a Mosaic. When new keys from
several calls are pending before execution begins, Mosaic can combine them into
one invocation. It does not intentionally wait for more keys, so exact batch
boundaries depend on scheduling. Choose perKeyTile for individual fetches or
chunkedMultiTile for smaller batches; callers keep the same API.
Choose a batching strategy β
Add org.buildmosaic:mosaic-core to a Kotlin/JVM project using the
installation guide for the latest
stable dependency coordinates.
No registration plugin or processor is needed. The optional BOM aligns the runtime library versions.
A Canvas holds application services and request data. A Mosaic runs Tiles and keeps their results. A Tile can read an input and call an ordinary service:
val OrderKey = CanvasKey(String::class, "orderKey")
val OrderTile by singleTile {
source<OrderService>().getOrder(source(OrderKey))
}The application creates the services and registers its existing instances with
Canvas. instance borrows them; the application retains ownership:
val applicationCanvas = canvas {
instance(orderService)
instance(customerService)
instance(productService)
instance(pricingService)
instance(addressService)
instance(carrierService)
}The framework examples show how each application creates these services. Bind the request input in a child Canvas, then ask for the page:
suspend fun orderPage(applicationCanvas: Canvas, orderId: String): OrderPage =
applicationCanvas.withLayer {
instance(OrderKey, orderId)
}.withMosaic { compose(OrderPageTile) }Import org.buildmosaic.core.injection.withMosaic. The calling coroutine owns Tile work;
leaving the block cancels unfinished work and waits for cleanup.
The complete quick start covers application setup, resource ownership, and runtime requirements. The Kotlin API aggregation guide walks through the order endpoint and shows how to check its HTTP response.
Mosaic follows semantic versioning for stable Runtime APIs. Runtime and optional Analysis are independently versioned. Find the supported Java and Kotlin versions, Runtime/Analysis combinations, and guarantees in the compatibility reference.
Your Tile graph is already an architecture model. The optional analysis plugin can turn it into documentationβthere's no separate graph to keep in sync by hand.
./gradlew mosaicGraphOrder architecture derived from mosaicGraph output.
Open build/reports/mosaic-analysis/graph.md for the full Markdown and Mermaid
graph, including what each Tile needs from Canvas and where it's bound. The plugin
can discover application entry points when safe and follow Tile dependencies
across modules.
It checks Canvas bindings and distinguishes confirmed missing dependencies from paths it can't verify. Analysis selects the appropriate compiler integration automatically for its supported Kotlin versions. Runtime composition doesn't depend on it. The graph shows static relationships, not runtime traces.
Set up architecture reports and verification β
Add Mosaic execution to your existing OpenTelemetry traces:
val applicationCanvas = canvas {
tracing { openTelemetry }
}The optional adapter creates one span per SingleTile execution or MultiTile batch,
using property names captured by delegated declarations such as
val OrderTile by singleTile { ... }. Unnamed Tiles use Mosaic single or Mosaic multi.
Links show shared producers and additional batch callers; cache hits create no new
spans. Your application owns sampling and export, and Mosaic records no keys,
results, or exception messages automatically.
openTelemetry is your application's configured instance.
Set up tracing and see the span semantics β
Tests can swap out dependency Tiles while leaving the page's composition untouched:
@Test
fun `order page combines summary and logistics`() = runTest {
mosaicBuilder()
.withMockTile(OrderSummaryTile, mockSummary)
.withMockTile(LogisticsTile, mockLogistics)
.withMosaic {
assertEquals(OrderPageTile, OrderPage(mockSummary, mockLogistics))
}
}mockSummary and mockLogistics are fixture values; the real OrderPageTile puts
them together. The testing guide covers setup, Canvas
inputs, failures, and delays simulated with coroutine virtual time.
In the published application benchmark, Mosaic used this much additional CPU against equivalent optimized Kotlin for the same downstream work:
| Workload | Additional Mosaic CPU/request |
|---|---|
| Light and batching | 14β21 Β΅s |
| Complex aggregate graph | 48β115 Β΅s |
| Independent sibling coalescing | 61β78 Β΅s |
| CPU-heavy | 6β9 Β΅s |
For the service-backed aggregate graph at 800 RPS, that was about 115 Β΅s of CPU/request, with median HTTP latency of about 21.12 ms for both implementations.
In the coalescing workload, six sibling Tiles independently discovered overlapping product keys. Mosaic fetched all 24 distinct products once, using one or two backend batches across 40 samples.
Timings depend on hardware and JVM. These application measurements apply to the source revision documented in the report. Performance evidence, workloads, and measurement limits β
Mosaic works alongside any HTTP framework; your framework owns routing, serialization, and server lifecycle. The same order Tiles run behind three example applications:
- Spring Boot β Controllers and application Canvas configuration
- Ktor β Coroutine route handlers
- Micronaut β Controllers and dependency injection
Mosaic is maintained by Nicholas Abbott (nick@buildmosaic.org). Use GitHub Issues for usage questions, bug reports, and feature requests; see the contribution guide for contribution and discussion routes.
For vulnerabilities, follow the security policy and email security@buildmosaic.org privately. Do not open a public issue. The policy limits security updates to the latest minor release.
Before adopting or upgrading, review runtime and optional analysis compatibility and release notes and upgrade guidance.
Licensed under Apache 2.0. See the Changelog for release history.
Copyright 2025 Nicholas Abbott
