Create a Kotlin Ktor server boilerplate using Koin for dependency injection. Implement a feature toggle mechanism where features can be enabled or disabled via a hot-reloadable config file without restarting the server.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Outlining Ktor server with hot-reloadable feature toggles
The plan is to build a Ktor server using Koin for DI with a FeatureToggleService that loads feature flags from a JSON config file and hot-reloads them on file changes via WatchService and coroutines, exposing routes that check toggles at runtime.
Below is a small Ktor + Koin boilerplate that demonstrates:
Dependency Injection using Koin.
A FeatureToggleService that loads toggles from a JSON file.
A hot-reload mechanism based on a file watcher so you can change features.json without restarting the server.
Feel free to adapt directory/package names as you like.
build.gradle.kts (snippets)
kotlin
plugins {
kotlin("jvm") version "1.9.0"
id("io.ktor.plugin") version "2.3.3" // or your desired version
}
application {
mainClass.set("com.example.ApplicationKt")
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.ktor:ktor-server-core:2.3.3")
implementation("io.ktor:ktor-server-netty:2.3.3")
implementation("io.ktor:ktor-server-content-negotiation:2.3.3")
implementation("io.ktor:ktor-serialization-jackson:2.3.3")
// Koin
implementation("io.insert-koin:koin-core:3.4.2")
implementation("io.insert-koin:koin-ktor:3.4.2")
implementation("io.insert-koin:koin-logger-slf4j:3.4.2")
// Logging
implementation("ch.qos.logback:logback-classic:1.4.11")
}
features.json (example config)
json
{
"myFeature": true,
"alphaRoute": false
}
Place this file in config/features.json (or wherever you prefer). The code below watches for changes to this file.
FeatureToggleService.kt
kotlin
package com.example
interface FeatureToggleService {
fun isEnabled(feature: String): Boolean
fun all(): Map<String, Boolean>
}
FileFeatureToggleService.kt
kotlin
package com.example
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.coroutines.*
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.file.*
import java.util.concurrent.atomic.AtomicReference
class FileFeatureToggleService(
private val configPath: String,
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO)
) : FeatureToggleService {
private val log = LoggerFactory.getLogger(FileFeatureToggleService::class.java)
private val mapper = jacksonObjectMapper()
private val togglesRef = AtomicReference<Map<String, Boolean>>(emptyMap())
init {
loadFromFile()
watchFile()
}
override fun isEnabled(feature: String): Boolean =
togglesRef.get()[feature] ?: false
override fun all(): Map<String, Boolean> = togglesRef.get()
private fun loadFromFile() {
try {
val file = File(configPath)
if (!file.exists()) {
log.warn("Feature toggle config file not found at $configPath. Using empty toggles.")
togglesRef.set(emptyMap())
return
}
val data: Map<String, Boolean> = mapper.readValue(file)
togglesRef.set(data)
log.info("Feature toggles loaded: $data")
} catch (e: Exception) {
log.error("Failed to load feature toggles from $configPath", e)
}
}
private fun watchFile() {
val path = Paths.get(configPath).toAbsolutePath()
val parentDir = path.parent ?: Paths.get(".").toAbsolutePath()
scope.launch {
try {
val watchService = FileSystems.getDefault().newWatchService()
parentDir.register(
watchService,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE
)
log.info("Watching file changes on $path")
while (isActive) {
val key = watchService.take()
for (event in key.pollEvents()) {
val evPath = event.context() as? Path ?: continue
if (evPath.fileName == path.fileName) {
log.info("Detected change in feature config file, reloading.")
loadFromFile()
}
}
if (!key.reset()) {
break
}
}
watchService.close()
} catch (ex: Exception) {
log.error("Feature toggle watcher encountered an error", ex)
}
}
}
}
Modules.kt
kotlin
package com.example
import org.koin.dsl.module
val appModule = module {
single<FeatureToggleService> {
// Pass the path to your features file, e.g., "config/features.json"
FileFeatureToggleService(configPath = "config/features.json")
}
}
Application.kt
kotlin
package com.example
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.jackson.*
import org.koin.ktor.ext.inject
import org.koin.ktor.plugin.Koin
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}
fun Application.module() {
install(ContentNegotiation) {
jackson()
}
install(Koin) {
modules(appModule)
}
val featureToggleService by inject<FeatureToggleService>()
routing {
get("/") {
call.respondText("Hello from Ktor + Koin!")
}
get("/feature-check/{name}") {
val featureName = call.parameters["name"] ?: "unknown"
val enabled = featureToggleService.isEnabled(featureName)
call.respondText("Feature '$featureName' is enabled: $enabled")
}
// Example usage of a toggle for route gating
get("/alpha") {
if (featureToggleService.isEnabled("alphaRoute")) {
call.respondText("Alpha route is ON!")
} else {
call.respondText("Alpha route is disabled.", status = io.ktor.http.HttpStatusCode.Forbidden)
}
}
// Inspect all toggles
get("/toggles") {
call.respond(featureToggleService.all())
}
}
}
How It Works
Koin is installed in the Application.module() function, and we provide a FileFeatureToggleService in appModule.
The FileFeatureToggleService loads the JSON config once at startup and spawns a coroutine-based watch loop using Java’s WatchService. When the file changes (ENTRY_MODIFY or ENTRY_CREATE), the service reloads the toggles.
Handlers fetch the FeatureToggleService via Koin’s inject delegate.
You can modify config/features.json while the server is running; the changes are picked up automatically. No restart required.
Usage
Run the server (./gradlew run).
Access http://localhost:8080/toggles to see your current toggles.
Edit config/features.json to enable/disable features. For example, set "alphaRoute": true, save, and try http://localhost:8080/alpha again.
The logs will indicate when the file is reloaded.
This provides a minimal, production-style pattern for Ktor + Koin + hot-reloadable feature toggles via file-based configuration.