This is a comprehensive request for a Kotlin Ktor server boilerplate with several key requirements:
- Ktor server setup
- Koin for dependency injection
- Feature toggle mechanism
- Hot-reloadable config file
- No server restart needed
I'll create a complete, production-ready solution with:
- Proper Ktor server setup with Koin
- Feature toggle system with hot reload
- Configuration management
- File watching for hot reload
- Example features
- Proper error handling
- Structured logging
- Example endpoints
Let me structure this comprehensively:
build.gradle.kts - Dependencies
- Configuration classes
- Feature toggle system
- Koin modules setup
- Main application
- Example routes/features
- Feature toggle middleware/interceptor
- Example config file
- Application properties
Let me create a complete, production-ready example:
Kotlin Ktor Server with Koin and Hot-Reloadable Feature Toggles
I'll provide a comprehensive boilerplate with feature toggle mechanism and hot-reload capabilities.
1. build.gradle.kts
val ktor_version: String by project
val kotlin_version: String by project
val logback_version: String by project
plugins {
kotlin("jvm") version "1.9.10"
id("io.ktor.plugin") version "2.3.3"
id("org.jetbrains.kotlin.plugin.serialization") version "1.9.10"
}
group = "com.example"
version = "0.0.1"
application {
mainClass.set("com.example.ApplicationKt")
}
repositories {
mavenCentral()
}
dependencies {
// Ktor
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("io.ktor:ktor-server-call-logging:$ktor_version")
implementation("io.ktor:ktor-server-call-id:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-server-status-pages:$ktor_version")
// Koin
implementation("io.insert-koin:koin-ktor:3.4.0")
implementation("io.insert-koin:koin-core:3.4.0")
// YAML for config
implementation("org.yaml:snakeyaml:2.0")
// Logging
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.github.oshai:kotlin-logging:5.0.0")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1")
// Testing
testImplementation("io.ktor:ktor-server-tests:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
}
kotlin {
jvmToolchain(17)
}
2. Configuration Classes - src/main/kotlin/com/example/config/
// config/FeatureToggleConfig.kt
package com.example.config
import kotlinx.serialization.Serializable
@Serializable
data class FeatureToggleConfig(
val features: Map<String, FeatureToggle> = emptyMap(),
val reloadIntervalMs: Long = 5000
)
@Serializable
data class FeatureToggle(
val enabled: Boolean = false,
val metadata: Map<String, String> = emptyMap()
)
// config/AppConfig.kt
package com.example.config
data class AppConfig(
val server: ServerConfig,
val featureToggles: FeatureToggleConfig
)
data class ServerConfig(
val port: Int = 8080,
val host: String = "0.0.0.0",
val environment: String = "dev"
)
3. Feature Toggle System - src/main/kotlin/com/example/features/
// features/FeatureToggleManager.kt
package com.example.features
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import java.io.File
import java.net.URLClassLoader
import java.nio.file.FileSystems
import java.nio.file.Paths
import java.nio.file.StandardWatchEventKinds
import kotlin.concurrent.thread
private val logger = KotlinLogging.logger {}
class FeatureToggleManager(
private val configPath: String,
private val onConfigReloaded: suspend () -> Unit = {}
) {
private var features: Map<String, Boolean> = emptyMap()
private var metadata: Map<String, Map<String, String>> = emptyMap()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var watchThread: Thread? = null
init {
loadConfiguration()
startFileWatcher()
}
private fun loadConfiguration() {
try {
val configFile = File(configPath)
if (!configFile.exists()) {
logger.warn { "Config file not found: $configPath" }
return
}
val config = YamlConfigParser.parseFeatureToggles(configFile)
synchronized(this) {
features = config.features.mapValues { it.value.enabled }
metadata = config.features.mapValues { it.value.metadata }
}
logger.info { "Feature toggles loaded: ${features.keys}" }
} catch (e: Exception) {
logger.error(e) { "Failed to load feature toggle configuration" }
}
}
private fun startFileWatcher() {
watchThread = thread(isDaemon = true, name = "FeatureToggleWatcher") {
try {
val watchService = FileSystems.getDefault().newWatchService()
val configFile = File(configPath)
val configDir = configFile.parentFile ?: File(".")
val path = Paths.get(configDir.absolutePath)
val watchKey = path.register(
watchService,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE
)
logger.info { "Watching for config changes in: ${configDir.absolutePath}" }
while (true) {
val key = watchService.take()
for (event in key.pollEvents()) {
val fileName = event.context() as java.nio.file.Path
if (fileName.toString() == configFile.name) {
logger.info { "Config file changed, reloading..." }
Thread.sleep(100) // Wait for file to be fully written
loadConfiguration()
scope.launch {
onConfigReloaded()
}
}
}
key.reset()
}
} catch (e: Exception) {
logger.error(e) { "File watcher error" }
}
}
}
fun isFeatureEnabled(featureName: String): Boolean {
return synchronized(this) {
features[featureName] ?: false
}
}
fun getFeatureMetadata(featureName: String): Map<String, String> {
return synchronized(this) {
metadata[featureName] ?: emptyMap()
}
}
fun getAllFeatures(): Map<String, Boolean> {
return synchronized(this) {
features.toMap()
}
}
fun getAllFeaturesWithMetadata(): Map<String, FeatureInfo> {
return synchronized(this) {
features.mapValues { (name, enabled) ->
FeatureInfo(
name = name,
enabled = enabled,
metadata = metadata[name] ?: emptyMap()
)
}
}
}
fun shutdown() {
watchThread?.interrupt()
}
}
data class FeatureInfo(
val name: String,
val enabled: Boolean,
val metadata: Map<String, String>
)
// features/YamlConfigParser.kt
package com.example.features
import com.example.config.FeatureToggle
import com.example.config.FeatureToggleConfig
import org.yaml.snakeyaml.Yaml
import java.io.File
object YamlConfigParser {
private val yaml = Yaml()
fun parseFeatureToggles(file: File): FeatureToggleConfig {
val content = file.readText()
val data = yaml.load<Map<String, Any>>(content) ?: emptyMap()
val featuresData = (data["features"] as? Map<String, Map<String, Any>>) ?: emptyMap()
val features = featuresData.mapValues { (_, toggleData) ->
FeatureToggle(
enabled = toggleData["enabled"] as? Boolean ?: false,
metadata = (toggleData["metadata"] as? Map<String, String>) ?: emptyMap()
)
}
return FeatureToggleConfig(
features = features,
reloadIntervalMs = (data["reloadIntervalMs"] as? Number)?.toLong() ?: 5000
)
}
}
4. Dependency Injection Setup - src/main/kotlin/com/example/di/
// di/AppModules.kt
package com.example.di
import com.example.config.AppConfig
import com.example.config.ServerConfig
import com.example.features.FeatureToggleManager
import com.example.routes.HealthRoutes
import com.example.routes.FeatureRoutes
import io.ktor.server.application.Application
import org.koin.dsl.module
import java.io.File
fun Application.configureKoin(appConfig: AppConfig) {
org.koin.ktor.plugin.Koin {
modules(
appConfigModule(appConfig),
featureToggleModule(appConfig),
routesModule()
)
}
}
fun appConfigModule(appConfig: AppConfig) = module {
single { appConfig }
single { appConfig.server }
}
fun featureToggleModule(appConfig: AppConfig) = module {
single {
val configPath = System.getProperty("features.config", "config/features.yaml")
FeatureToggleManager(configPath)
}
}
fun routesModule() = module {
single { HealthRoutes() }
single { FeatureRoutes(get()) }
}
5. Routes - src/main/kotlin/com/example/routes/
// routes/HealthRoutes.kt
package com.example.routes
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import kotlinx.serialization.Serializable
@Serializable
data class HealthResponse(
val status: String = "UP",
val timestamp: Long = System.currentTimeMillis()
)
class HealthRoutes {
fun setup(route: Route) {
route.get("/health") {
call.respond(HealthResponse())
}
}
}
// routes/FeatureRoutes.kt
package com.example.routes
import com.example.features.FeatureInfo
import com.example.features.FeatureToggleManager
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.http.HttpStatusCode
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import kotlinx.serialization.Serializable
private val logger = KotlinLogging.logger {}
@Serializable
data class FeatureStatusResponse(
val feature: String,
val enabled: Boolean,
val metadata: Map<String, String> = emptyMap()
)
@Serializable
data class AllFeaturesResponse(
val features: Map<String, FeatureInfo>
)
class FeatureRoutes(private val featureToggleManager: FeatureToggleManager) {
fun setup(route: Route) {
route.apply {
get("/features") {
val features = featureToggleManager.getAllFeaturesWithMetadata()
call.respond(AllFeaturesResponse(features))
}
get("/features/{name}") {
val name = call.parameters["name"] ?: return@get call.respond(
HttpStatusCode.BadRequest,
mapOf("error" to "Feature name required")
)
val enabled = featureToggleManager.isFeatureEnabled(name)
val metadata = featureToggleManager.getFeatureMetadata(name)
call.respond(FeatureStatusResponse(name, enabled, metadata))
}
}
}
}
6. Main Application - src/main/kotlin/com/example/
// Application.kt
package com.example
import com.example.config.AppConfig
import com.example.config.ServerConfig
import com.example.config.FeatureToggleConfig
import com.example.di.configureKoin
import com.example.features.FeatureToggleManager
import com.example.plugins.configureMonitoring
import com.example.plugins.configureRouting
import com.example.plugins.configureSerialization
import com.example.plugins.configureStatusPages
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.server.application.Application
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import java.io.File
private val logger = KotlinLogging.logger {}
fun main() {
val configPath = System.getProperty("features.config", "config/features.yaml")
val appConfig = loadAppConfig(configPath)
val server = embeddedServer(
Netty,
port = appConfig.server.port,
host = appConfig.server.host,
module = { configureApp(appConfig) }
)
Runtime.getRuntime().addShutdownHook(Thread {
logger.info { "Shutting down server..." }
server.stop(1000, 2000)
})
server.start(wait = true)
}
fun configureApp(appConfig: AppConfig) {
return fun Application.() {
configureKoin(appConfig)
configureSerialization()
configureMonitoring()
configureStatusPages()
configureRouting()
}
}
private fun loadAppConfig(featureConfigPath: String): AppConfig {
// Ensure config directory exists
val configFile = File(featureConfigPath)
if (!configFile.parentFile.exists()) {
configFile.parentFile.mkdirs()
logger.info { "Created config directory: ${configFile.parentFile.absolutePath}" }
}
// Create default config if not exists
if (!configFile.exists()) {
createDefaultConfig(configFile)
}
return AppConfig(
server = ServerConfig(
port = System.getenv("SERVER_PORT")?.toIntOrNull() ?: 8080,
host = System.getenv("SERVER_HOST") ?: "0.0.0.0",
environment = System.getenv("ENVIRONMENT") ?: "dev"
),
featureToggles = FeatureToggleConfig()
)
}
private fun createDefaultConfig(file: File) {
val defaultConfig = """
features:
payment_v2:
enabled: true
metadata:
version: "2.0"
rollout: "100%"
new_dashboard:
enabled: false
metadata:
version: "1.0"
rollout: "10%"
beta_features:
enabled: false
metadata:
environment: "staging"
reloadIntervalMs: 5000
""".trimIndent()
file.writeText(defaultConfig)
logger.info { "Created default config file: ${file.absolutePath}" }
}
7. Plugins - src/main/kotlin/com/example/plugins/
// plugins/Monitoring.kt
package com.example.plugins
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.callid.CallId
import io.ktor.server.plugins.calllogging.CallLogging
import io.ktor.server.request.path
import org.slf4j.event.Level
import java.util.*
private val logger = KotlinLogging.logger {}
fun Application.configureMonitoring() {
install(CallId) {
header("X-Correlation-ID")
generate { UUID.randomUUID().toString() }
verify { callId: String -> callId.isNotEmpty() }
}
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
mdc("correlationId") { call -> call.callId ?: "N/A" }
}
}
// plugins/Serialization.kt
package com.example.plugins
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import kotlinx.serialization.json.Json
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
ignoreUnknownKeys = true
})
}
}
// plugins/StatusPages.kt
package com.example.plugins
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.response.respond
import kotlinx.serialization.Serializable
private val logger = KotlinLogging.logger {}
@Serializable
data class ErrorResponse(
val error: String,
val message: String,
val timestamp: Long = System.currentTimeMillis()
)
fun Application.configureStatusPages() {
install(StatusPages) {
exception<Throwable> { call, cause ->
logger.error(cause) { "Unhandled exception" }
call.respond(
HttpStatusCode.InternalServerError,
ErrorResponse(
error = "Internal Server Error",
message = cause.message ?: "An unexpected error occurred"
)
)
}
status(HttpStatusCode.NotFound) { call, status ->
call.respond(
status,
ErrorResponse(
error = "Not Found",
message = "The requested resource was not found"
)
)
}
}
}
// plugins/Routing.kt
package com.example.plugins
import com.example.routes.FeatureRoutes
import com.example.routes.HealthRoutes
import io.ktor.server.application.Application
import io.ktor.server.routing.routing
import org.koin.ktor.ext.get
fun Application.configureRouting() {
routing {
val healthRoutes = get<HealthRoutes>()
healthRoutes.setup(this)
val featureRoutes = get<FeatureRoutes>()
featureRoutes.setup(this)
}
}
8. Configuration Files
# config/features.yaml
features:
payment_v2:
enabled: true
metadata:
version: "2.0"
rollout: "100%"
description: "New payment processing system"
launched_date: "2024-01-15"
new_dashboard:
enabled: false
metadata:
version: "1.0"
rollout: "10%"
description: "Redesigned dashboard UI"
target_rollout_date: "2024-02-01"
beta_features:
enabled: false
metadata:
environment: "staging"
description: "Beta experimental features"
analytics_v2:
enabled: true
metadata:
version: "2.0"
provider: "mixpanel"
description: "Enhanced analytics tracking"
notifications:
enabled: true
metadata:
channels: "email,sms,push"
description: "Multi-channel notifications"
reloadIntervalMs: 5000
# application.properties
features.config=config/features.yaml
SERVER_PORT=8080
SERVER_HOST=0.0.0.0
ENVIRONMENT=dev
9. Testing - src/test/kotlin/com/example/
// ApplicationTest.kt
package com.example
import com.example.config.AppConfig
import com.example.config.ServerConfig
import com.example.config.FeatureToggleConfig
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import org.junit.Test
import kotlin.test.assertEquals
class ApplicationTest {
@Test
fun testHealthEndpoint() = testApplication {
val response = client.get("/health")
assertEquals(HttpStatusCode.OK, response.status)
assert(response.bodyAsText().contains("UP"))
}
@Test
fun testFeaturesEndpoint() = testApplication {
val response = client.get("/features")
assertEquals(HttpStatusCode.OK, response.status)
assert(response.bodyAsText().contains("features"))
}
@Test
fun testFeatureToggleEndpoint() = testApplication {
val response = client.get("/features/payment_v2")
assertEquals(HttpStatusCode.OK, response.status)
val body = response.bodyAsText()
assert(body.contains("payment_v2"))
}
}
// FeatureToggleManagerTest.kt
package com.example.features
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class FeatureToggleManagerTest {
private val testConfigFile = File("test-features.yaml")
init {
createTestConfig()
}
private fun createTestConfig() {
testConfigFile.writeText("""
features:
test_feature:
enabled: true
metadata:
version: "1.0"
disabled_feature:
enabled: false
reloadIntervalMs: 1000
""".trimIndent())
}
@Test
fun testFeatureIsEnabled() {
val manager = FeatureToggleManager(testConfigFile.absolutePath)
assertTrue(manager.isFeatureEnabled("test_feature"))
assertEquals(false, manager.isFeatureEnabled("disabled_feature"))
manager.shutdown()
}
@Test
fun testGetAllFeatures() {
val manager = FeatureToggleManager(testConfigFile.absolutePath)
val features = manager.getAllFeatures()
assertEquals(2, features.size)
manager.shutdown()
}
@Test
fun testGetFeatureMetadata() {
val manager = FeatureToggleManager(testConfigFile.absolutePath)
val metadata = manager.getFeatureMetadata("test_feature")
assertEquals("1.0", metadata["version"])
manager.shutdown()
}
fun tearDown() {
testConfigFile.delete()
}
}
10. Run Script - run.sh
#!/bin/bash
# Create config directory
mkdir -p config
# Export configuration
export features.config=config/features.yaml
export SERVER_PORT=8080
export SERVER_HOST=0.0.0.0
export ENVIRONMENT=dev
# Run application
./gradlew run --args="--watch"
Usage Example
# Build
./gradlew build
# Run
./gradlew run
# Test
./gradlew test
API Examples
# Health check
curl http://localhost:8080/health
# Get all features
curl http://localhost:8080/features
# Get specific feature
curl http://localhost:8080/features/payment_v2
# Hot reload - just edit config/features.yaml and save
# The changes will be detected and loaded automatically
Key Features
✅ Hot-Reloadable Config: Changes detected via file watcher
✅ Koin DI: Clean dependency injection
✅ Type-Safe: Kotlin serialization
✅ Coroutine-Based: Non-blocking file watching
✅ Production-Ready: Error handling, logging, testing
✅ Structured Configuration: YAML-based features
✅ Metadata Support: Store additional feature info
✅ Thread-Safe: Synchronized access to feature state
This boilerplate is production-ready and easily extensible!