0
# Engine Implementation
1
2
Core server engine implementation providing lifecycle management, connection handling, and integration with Ktor's application pipeline.
3
4
## Capabilities
5
6
### NettyApplicationEngine Class
7
8
Main engine implementation that manages the HTTP server lifecycle, Netty bootstrap configuration, and event loop groups.
9
10
```kotlin { .api }
11
/**
12
* ApplicationEngine implementation for running in a standalone Netty environment
13
*/
14
class NettyApplicationEngine(
15
environment: ApplicationEnvironment,
16
monitor: Events,
17
developmentMode: Boolean,
18
val configuration: Configuration,
19
applicationProvider: () -> Application
20
) : BaseApplicationEngine(environment, monitor, developmentMode) {
21
22
/**
23
* Engine configuration access
24
*/
25
val configuration: Configuration
26
27
/**
28
* Start the HTTP server
29
* @param wait If true, blocks until server is stopped
30
* @return This NettyApplicationEngine instance for chaining
31
*/
32
fun start(wait: Boolean): NettyApplicationEngine
33
34
/**
35
* Stop the server gracefully
36
* @param gracePeriodMillis Grace period for ongoing requests
37
* @param timeoutMillis Maximum time to wait for shutdown
38
*/
39
fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
40
41
/**
42
* String representation of the engine
43
* @return String representation including environment information
44
*/
45
override fun toString(): String
46
}
47
```
48
49
**Usage Examples:**
50
51
```kotlin
52
import io.ktor.server.application.*
53
import io.ktor.server.engine.*
54
import io.ktor.server.netty.*
55
import io.ktor.events.*
56
57
// Manual engine creation and lifecycle management
58
val environment = applicationEngineEnvironment {
59
connector {
60
port = 8080
61
host = "0.0.0.0"
62
}
63
module {
64
// Application configuration
65
}
66
}
67
68
val configuration = NettyApplicationEngine.Configuration().apply {
69
runningLimit = 64
70
tcpKeepAlive = true
71
}
72
73
val engine = NettyApplicationEngine(
74
environment = environment,
75
monitor = Events(),
76
developmentMode = false,
77
configuration = configuration,
78
applicationProvider = { environment.application }
79
)
80
81
// Start server
82
engine.start(wait = false)
83
84
// Perform other operations...
85
86
// Stop server gracefully
87
engine.stop(gracePeriodMillis = 1000, timeoutMillis = 5000)
88
```
89
90
### Server Lifecycle Management
91
92
The engine provides comprehensive lifecycle management with proper resource cleanup and graceful shutdown.
93
94
**Startup Process:**
95
1. Initialize EventLoopGroups (connection, worker, call)
96
2. Configure ServerBootstrap with connectors
97
3. Bind to network interfaces
98
4. Register shutdown hooks
99
5. Raise ServerReady event
100
101
**Shutdown Process:**
102
1. Stop accepting new connections
103
2. Complete ongoing requests within grace period
104
3. Shutdown EventLoopGroups
105
4. Close network channels
106
5. Release resources
107
108
```kotlin
109
// Graceful shutdown with custom timeouts
110
engine.start(wait = false)
111
112
// Register shutdown hook for graceful termination
113
Runtime.getRuntime().addShutdownHook(Thread {
114
engine.stop(
115
gracePeriodMillis = 5000, // Allow 5 seconds for requests to complete
116
timeoutMillis = 10000 // Force shutdown after 10 seconds total
117
)
118
})
119
```
120
121
### Event Loop Group Management
122
123
The engine automatically manages EventLoopGroups for different purposes, optimizing for platform-specific implementations.
124
125
**Event Loop Groups:**
126
- **Connection Group**: Accepts incoming connections
127
- **Worker Group**: Handles I/O operations and HTTP processing
128
- **Call Group**: Processes application calls (can be shared with worker group)
129
130
```kotlin
131
// Configuration affecting event loop management
132
val configuration = NettyApplicationEngine.Configuration().apply {
133
connectionGroupSize = 1 // Single thread for accepting connections
134
workerGroupSize = 8 // 8 threads for I/O operations
135
callGroupSize = 16 // 16 threads for application processing
136
shareWorkGroup = false // Use separate call group
137
}
138
```
139
140
### Bootstrap Configuration
141
142
The engine provides hooks for customizing Netty's ServerBootstrap configuration.
143
144
```kotlin
145
import io.netty.channel.ChannelOption
146
import io.netty.channel.WriteBufferWaterMark
147
148
val configuration = NettyApplicationEngine.Configuration().apply {
149
configureBootstrap = {
150
// Connection backlog
151
option(ChannelOption.SO_BACKLOG, 1024)
152
153
// Child channel options
154
childOption(ChannelOption.SO_KEEPALIVE, true)
155
childOption(ChannelOption.TCP_NODELAY, true)
156
childOption(ChannelOption.SO_REUSEADDR, true)
157
158
// Buffer configuration
159
childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
160
WriteBufferWaterMark(32 * 1024, 64 * 1024))
161
}
162
}
163
```
164
165
### Channel Pipeline Configuration
166
167
Custom channel pipeline configuration for adding handlers or modifying the processing chain.
168
169
```kotlin
170
import io.netty.handler.logging.LoggingHandler
171
import io.netty.handler.logging.LogLevel
172
173
val configuration = NettyApplicationEngine.Configuration().apply {
174
channelPipelineConfig = {
175
// Add logging handler for debugging
176
addFirst("logging", LoggingHandler(LogLevel.DEBUG))
177
178
// Add custom handlers
179
addLast("custom-handler", MyCustomHandler())
180
}
181
}
182
```
183
184
### Error Handling and Monitoring
185
186
The engine integrates with Ktor's event monitoring system for tracking server state and errors.
187
188
```kotlin
189
import io.ktor.events.*
190
import io.ktor.server.engine.*
191
192
val events = Events()
193
194
// Subscribe to server events
195
events.subscribe(ServerReady) { environment ->
196
println("Server started on ${environment.connectors}")
197
}
198
199
events.subscribe(ApplicationStopPreparing) { environment ->
200
println("Server shutdown initiated")
201
}
202
203
val engine = NettyApplicationEngine(
204
environment = environment,
205
monitor = events,
206
developmentMode = false,
207
configuration = configuration,
208
applicationProvider = { environment.application }
209
)
210
```
211
212
### Platform Channel Selection
213
214
The engine automatically selects optimal channel implementations based on the platform:
215
216
- **Linux**: EpollServerSocketChannel (native epoll)
217
- **macOS**: KQueueServerSocketChannel (native kqueue)
218
- **Windows/Other**: NioServerSocketChannel (NIO fallback)
219
220
```kotlin { .api }
221
/**
222
* Get optimal channel class for the current platform
223
* @return KClass of the most suitable ServerSocketChannel implementation
224
*/
225
internal fun getChannelClass(): KClass<out ServerSocketChannel>
226
```
227
228
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.