CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-server-netty-jvm

Netty-based HTTP server engine for Ktor framework providing high-performance asynchronous server capabilities

Pending
Overview
Eval results
Files

engine-implementation.mddocs/

Engine Implementation

Core server engine implementation providing lifecycle management, connection handling, and integration with Ktor's application pipeline.

Capabilities

NettyApplicationEngine Class

Main engine implementation that manages the HTTP server lifecycle, Netty bootstrap configuration, and event loop groups.

/**
 * ApplicationEngine implementation for running in a standalone Netty environment
 */
class NettyApplicationEngine(
    environment: ApplicationEnvironment,
    monitor: Events,
    developmentMode: Boolean,
    val configuration: Configuration,
    applicationProvider: () -> Application
) : BaseApplicationEngine(environment, monitor, developmentMode) {
    
    /**
     * Engine configuration access
     */
    val configuration: Configuration
    
    /**
     * Start the HTTP server
     * @param wait If true, blocks until server is stopped
     * @return This NettyApplicationEngine instance for chaining
     */
    fun start(wait: Boolean): NettyApplicationEngine
    
    /**
     * Stop the server gracefully
     * @param gracePeriodMillis Grace period for ongoing requests
     * @param timeoutMillis Maximum time to wait for shutdown
     */
    fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
    
    /**
     * String representation of the engine
     * @return String representation including environment information
     */
    override fun toString(): String
}

Usage Examples:

import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.events.*

// Manual engine creation and lifecycle management
val environment = applicationEngineEnvironment {
    connector {
        port = 8080
        host = "0.0.0.0"
    }
    module {
        // Application configuration
    }
}

val configuration = NettyApplicationEngine.Configuration().apply {
    runningLimit = 64
    tcpKeepAlive = true
}

val engine = NettyApplicationEngine(
    environment = environment,
    monitor = Events(),
    developmentMode = false,
    configuration = configuration,
    applicationProvider = { environment.application }
)

// Start server
engine.start(wait = false)

// Perform other operations...

// Stop server gracefully
engine.stop(gracePeriodMillis = 1000, timeoutMillis = 5000)

Server Lifecycle Management

The engine provides comprehensive lifecycle management with proper resource cleanup and graceful shutdown.

Startup Process:

  1. Initialize EventLoopGroups (connection, worker, call)
  2. Configure ServerBootstrap with connectors
  3. Bind to network interfaces
  4. Register shutdown hooks
  5. Raise ServerReady event

Shutdown Process:

  1. Stop accepting new connections
  2. Complete ongoing requests within grace period
  3. Shutdown EventLoopGroups
  4. Close network channels
  5. Release resources
// Graceful shutdown with custom timeouts
engine.start(wait = false)

// Register shutdown hook for graceful termination
Runtime.getRuntime().addShutdownHook(Thread {
    engine.stop(
        gracePeriodMillis = 5000,  // Allow 5 seconds for requests to complete
        timeoutMillis = 10000      // Force shutdown after 10 seconds total
    )
})

Event Loop Group Management

The engine automatically manages EventLoopGroups for different purposes, optimizing for platform-specific implementations.

Event Loop Groups:

  • Connection Group: Accepts incoming connections
  • Worker Group: Handles I/O operations and HTTP processing
  • Call Group: Processes application calls (can be shared with worker group)
// Configuration affecting event loop management
val configuration = NettyApplicationEngine.Configuration().apply {
    connectionGroupSize = 1        // Single thread for accepting connections
    workerGroupSize = 8           // 8 threads for I/O operations
    callGroupSize = 16            // 16 threads for application processing
    shareWorkGroup = false        // Use separate call group
}

Bootstrap Configuration

The engine provides hooks for customizing Netty's ServerBootstrap configuration.

import io.netty.channel.ChannelOption
import io.netty.channel.WriteBufferWaterMark

val configuration = NettyApplicationEngine.Configuration().apply {
    configureBootstrap = {
        // Connection backlog
        option(ChannelOption.SO_BACKLOG, 1024)
        
        // Child channel options
        childOption(ChannelOption.SO_KEEPALIVE, true)
        childOption(ChannelOption.TCP_NODELAY, true)
        childOption(ChannelOption.SO_REUSEADDR, true)
        
        // Buffer configuration
        childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, 
                   WriteBufferWaterMark(32 * 1024, 64 * 1024))
    }
}

Channel Pipeline Configuration

Custom channel pipeline configuration for adding handlers or modifying the processing chain.

import io.netty.handler.logging.LoggingHandler
import io.netty.handler.logging.LogLevel

val configuration = NettyApplicationEngine.Configuration().apply {
    channelPipelineConfig = {
        // Add logging handler for debugging
        addFirst("logging", LoggingHandler(LogLevel.DEBUG))
        
        // Add custom handlers
        addLast("custom-handler", MyCustomHandler())
    }
}

Error Handling and Monitoring

The engine integrates with Ktor's event monitoring system for tracking server state and errors.

import io.ktor.events.*
import io.ktor.server.engine.*

val events = Events()

// Subscribe to server events
events.subscribe(ServerReady) { environment ->
    println("Server started on ${environment.connectors}")
}

events.subscribe(ApplicationStopPreparing) { environment ->
    println("Server shutdown initiated")
}

val engine = NettyApplicationEngine(
    environment = environment,
    monitor = events,
    developmentMode = false,
    configuration = configuration,
    applicationProvider = { environment.application }
)

Platform Channel Selection

The engine automatically selects optimal channel implementations based on the platform:

  • Linux: EpollServerSocketChannel (native epoll)
  • macOS: KQueueServerSocketChannel (native kqueue)
  • Windows/Other: NioServerSocketChannel (NIO fallback)
/**
 * Get optimal channel class for the current platform
 * @return KClass of the most suitable ServerSocketChannel implementation
 */
internal fun getChannelClass(): KClass<out ServerSocketChannel>

This function is used internally by the engine to automatically select the best-performing channel implementation for the current operating system, providing optimal performance without requiring manual configuration.

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-server-netty-jvm

docs

coroutine-integration.md

engine-implementation.md

index.md

platform-optimization.md

request-response.md

server-configuration.md

standalone-server.md

tile.json