router.rs 14.8 KB
Newer Older
1
use crate::tree::Tree;
2
3
4
use actix_web::http::header::{HeaderValue, CONTENT_TYPE};
use actix_web::{HttpRequest, HttpResponse};
use bytes::Bytes;
Byron Hsu's avatar
Byron Hsu committed
5
use futures_util::{StreamExt, TryStreamExt};
6
use log::{debug, info};
7
use std::collections::HashMap;
8
use std::fmt::Debug;
9
10
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Mutex};
11
12
use std::thread;
use std::time::Duration;
13
14

#[derive(Debug)]
15
16
17
pub enum Router {
    RoundRobin {
        worker_urls: Vec<String>,
18
        current_index: AtomicUsize,
19
20
21
22
    },
    Random {
        worker_urls: Vec<String>,
    },
23
24
    CacheAware {
        /*
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            Cache-Aware Load Balancing Router

            This router combines two strategies to optimize both cache utilization and request distribution:

            1. Cache-Aware Routing (Approximate Tree)
            2. Load Balancing (Shortest Queue with Balance Thresholds)

            The router dynamically switches between these strategies based on load conditions:
            - Uses load balancing when the system is imbalanced
            - Uses cache-aware routing when the system is balanced

            A system is considered imbalanced if both conditions are met:
            1. (max - min) > abs_threshold
            2. max > rel_threshold * min

            Strategy Details:

            1. Cache-Aware Routing (Approximate Tree)
            -------------------------------------------
            This strategy maintains an approximate radix tree for each worker based on request history,
            eliminating the need for direct cache state queries. The tree stores raw text characters
            instead of token IDs to avoid tokenization overhead.

            Process:
            a. For each request, find the worker with the highest prefix match
            b. If match rate > cache_threshold:
            Route to the worker with highest match (likely has relevant data cached)
            c. If match rate ≤ cache_threshold:
            Route to the worker with smallest tree size (most available cache capacity)
            d. Background maintenance:
            Periodically evict least recently used leaf nodes to prevent memory overflow

            2. Load Balancing (Shortest Queue)
            -------------------------------------------
            This strategy tracks pending request counts per worker and routes new requests
            to the least busy worker when the system is detected to be imbalanced.

            Configuration Parameters:
            ------------------------
            1. cache_threshold: (float, 0.0 to 1.0)
            Minimum prefix match ratio to use highest-match routing.
            Below this threshold, routes to worker with most available cache space.

            2. balance_abs_threshold: (integer)
            Absolute difference threshold for load imbalance detection.
            System is potentially imbalanced if (max_load - min_load) > abs_threshold

            3. balance_rel_threshold: (float)
            Relative ratio threshold for load imbalance detection.
            System is potentially imbalanced if max_load > min_load * rel_threshold
            Used in conjunction with abs_threshold to determine final imbalance state.

            4. eviction_interval_secs: (integer)
            Interval between LRU eviction cycles for the approximate trees.

            5. max_tree_size: (integer)
            Maximum nodes per tree. When exceeded, LRU leaf nodes are evicted
            during the next eviction cycle.
83
        */
84
        worker_urls: Vec<String>,
85
86
87
        tree: Arc<Mutex<Tree>>,
        running_queue: Arc<Mutex<HashMap<String, usize>>>,
        processed_queue: Arc<Mutex<HashMap<String, usize>>>,
88
        cache_threshold: f32,
89
90
91
        balance_abs_threshold: usize,
        balance_rel_threshold: f32,
        _eviction_thread: Option<thread::JoinHandle<()>>,
92
93
94
    },
}

95
#[derive(Debug)]
96
97
98
pub enum PolicyConfig {
    RandomConfig,
    RoundRobinConfig,
99
    CacheAwareConfig {
100
        cache_threshold: f32,
101
102
        balance_abs_threshold: usize,
        balance_rel_threshold: f32,
103
104
        eviction_interval_secs: u64,
        max_tree_size: usize,
105
106
107
    },
}

108
109
fn get_text_from_request(body: &Bytes, route: &str) -> String {
    // convert body to json
110
    let json = serde_json::from_slice::<serde_json::Value>(body).unwrap();
111

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    if route == "generate" {
        // get the "text" field
        let text = json.get("text").and_then(|t| t.as_str()).unwrap_or("");
        return text.to_string();
    } else if route == "v1/chat/completions" {
        // get the messages field as raw text
        if let Some(messages) = json.get("messages") {
            // Convert messages back to a string, preserving all JSON formatting
            return serde_json::to_string(messages).unwrap_or_default();
        }
    } else if route == "v1/completions" {
        let prompt = json.get("prompt").and_then(|t| t.as_str()).unwrap_or("");
        return prompt.to_string();
    }

    return "".to_string();
}
129
impl Router {
130
131
132
133
    pub fn new(worker_urls: Vec<String>, policy_config: PolicyConfig) -> Self {
        match policy_config {
            PolicyConfig::RandomConfig => Router::Random { worker_urls },
            PolicyConfig::RoundRobinConfig => Router::RoundRobin {
134
135
136
                worker_urls,
                current_index: std::sync::atomic::AtomicUsize::new(0),
            },
137
            PolicyConfig::CacheAwareConfig {
138
                cache_threshold,
139
140
                balance_abs_threshold,
                balance_rel_threshold,
141
142
                eviction_interval_secs,
                max_tree_size,
143
            } => {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
                let mut running_queue = HashMap::new();
                for url in &worker_urls {
                    running_queue.insert(url.clone(), 0);
                }

                let mut processed_queue = HashMap::new();
                for url in &worker_urls {
                    processed_queue.insert(url.clone(), 0);
                }

                let tree = Arc::new(Mutex::new(Tree::new()));
                let running_queue = Arc::new(Mutex::new(running_queue));
                let processed_queue = Arc::new(Mutex::new(processed_queue));

                // Create background eviction thread
                let tree_clone = Arc::clone(&tree);
                let processed_queue_clone = Arc::clone(&processed_queue);
161
                let running_queue_clone = Arc::clone(&running_queue);
162
163
164
165
166
167
168
169
170
171
172
                let eviction_thread = thread::spawn(move || {
                    loop {
                        // Sleep for the specified interval
                        thread::sleep(Duration::from_secs(eviction_interval_secs));

                        let locked_tree_clone = tree_clone.lock().unwrap();
                        // Run eviction
                        locked_tree_clone.evict_tenant_data(max_tree_size);

                        // Print the process queue
                        let locked_processed_queue = processed_queue_clone.lock().unwrap();
173
                        info!("Processed Queue: {:?}", locked_processed_queue);
174
175
176

                        // Print the running queue
                        let locked_running_queue = running_queue_clone.lock().unwrap();
177
                        info!("Running Queue: {:?}", locked_running_queue);
178
179
                    }
                });
180
181

                for url in &worker_urls {
182
                    tree.lock().unwrap().insert(&"".to_string(), url);
183
184
                }

185
                Router::CacheAware {
186
                    worker_urls,
187
188
189
                    tree,
                    running_queue,
                    processed_queue,
190
                    cache_threshold,
191
192
                    balance_abs_threshold,
                    balance_rel_threshold,
193
                    _eviction_thread: Some(eviction_thread),
194
195
                }
            }
196
197
198
        }
    }

199
200
    pub fn get_first(&self) -> Option<String> {
        match self {
201
202
            Router::RoundRobin { worker_urls, .. }
            | Router::Random { worker_urls }
203
            | Router::CacheAware { worker_urls, .. } => {
204
205
206
207
208
209
                if worker_urls.is_empty() {
                    None
                } else {
                    Some(worker_urls[0].clone())
                }
            }
210
211
212
        }
    }

213
214
215
216
217
    pub async fn dispatch(
        &self,
        client: &reqwest::Client,
        req: HttpRequest,
        body: Bytes,
218
        route: &str,
219
    ) -> HttpResponse {
220
        let text = get_text_from_request(&body, route);
221

222
223
224
225
226
        let worker_url = match self {
            Router::RoundRobin {
                worker_urls,
                current_index,
            } => {
227
                let idx = current_index
228
229
230
231
232
                    .fetch_update(
                        std::sync::atomic::Ordering::SeqCst,
                        std::sync::atomic::Ordering::SeqCst,
                        |x| Some((x + 1) % worker_urls.len()),
                    )
233
234
                    .unwrap();
                worker_urls[idx].clone()
235
            }
236

237
            Router::Random { worker_urls } => {
238
239
240
                worker_urls[rand::random::<usize>() % worker_urls.len()].clone()
            }

241
            Router::CacheAware {
242
                worker_urls,
243
244
245
                tree,
                running_queue,
                processed_queue,
246
                cache_threshold,
247
248
                balance_abs_threshold,
                balance_rel_threshold,
249
250
                ..
            } => {
251
                // TODO: delay scheduling if cache hit rate is high because it may cause imbalance. prioritize low hit rate ones
252

Byron Hsu's avatar
Byron Hsu committed
253
                let tree = tree.lock().unwrap();
254
                let mut running_queue = running_queue.lock().unwrap();
255

256
257
258
259
260
261
262
263
264
265
266
267
                // Get current load statistics
                let max_load = *running_queue.values().max().unwrap_or(&0);
                let min_load = *running_queue.values().min().unwrap_or(&0);

                // Load is considered imbalanced if:
                // 1. (max - min) > abs_threshold AND
                // 2. max > rel_threshold * min
                let is_imbalanced = max_load.saturating_sub(min_load) > *balance_abs_threshold
                    && (max_load as f32) > (min_load as f32 * balance_rel_threshold);

                let selected_url = if is_imbalanced {
                    // Log load balancing trigger and current queue state
268
                    info!(
269
270
271
272
273
274
275
276
277
278
279
280
281
282
                        "Load balancing triggered due to workload imbalance:\n\
                        Max load: {}, Min load: {}\n\
                        Current running queue: {:?}",
                        max_load, min_load, running_queue
                    );

                    // Use shortest queue routing when load is imbalanced
                    running_queue
                        .iter()
                        .min_by_key(|(_url, &count)| count)
                        .map(|(url, _)| url.clone())
                        .unwrap_or_else(|| worker_urls[0].clone())
                } else {
                    // Use cache-aware routing when load is balanced
283
284
285
                    let (matched_text, matched_worker) = tree.prefix_match(&text);
                    let matched_rate =
                        matched_text.chars().count() as f32 / text.chars().count() as f32;
286

287
288
289
290
                    if matched_rate > *cache_threshold {
                        matched_worker.to_string()
                    } else {
                        tree.get_smallest_tenant()
291
                    }
292
                };
293

294
295
                // Update queues and tree
                *running_queue.get_mut(&selected_url).unwrap() += 1;
296

297
298
299
300
301
                *processed_queue
                    .lock()
                    .unwrap()
                    .get_mut(&selected_url)
                    .unwrap() += 1;
302
303
304
                tree.insert(&text, &selected_url);

                selected_url
305
306
            }
        };
307

308
309
310
        let is_stream = serde_json::from_slice::<serde_json::Value>(&body)
            .map(|v| v.get("stream").and_then(|s| s.as_bool()).unwrap_or(false))
            .unwrap_or(false);
311

312
        let res = match client
313
            .post(format!("{}/{}", worker_url.clone(), route))
314
315
316
317
318
319
320
321
322
323
324
325
326
327
            .header(
                "Content-Type",
                req.headers()
                    .get("Content-Type")
                    .and_then(|h| h.to_str().ok())
                    .unwrap_or("application/json"),
            )
            .body(body.to_vec())
            .send()
            .await
        {
            Ok(res) => res,
            Err(_) => return HttpResponse::InternalServerError().finish(),
        };
328

329
330
        let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);
331

332
        if !is_stream {
333
334
            // For non-streaming requests, get response first
            let response = match res.bytes().await {
335
336
                Ok(body) => HttpResponse::build(status).body(body.to_vec()),
                Err(_) => HttpResponse::InternalServerError().finish(),
337
338
339
340
341
342
343
344
345
            };

            // Then decrement running queue counter if using CacheAware
            if let Router::CacheAware { running_queue, .. } = self {
                if let Ok(mut queue) = running_queue.lock() {
                    if let Some(count) = queue.get_mut(&worker_url) {
                        *count = count.saturating_sub(1);
                    }
                }
346
            }
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

            response
        } else if let Router::CacheAware { running_queue, .. } = self {
            let running_queue = Arc::clone(running_queue);
            let worker_url = worker_url.clone();

            HttpResponse::build(status)
                .insert_header((CONTENT_TYPE, HeaderValue::from_static("text/event-stream")))
                .streaming(
                    res.bytes_stream()
                        .map_err(|_| {
                            actix_web::error::ErrorInternalServerError("Failed to read stream")
                        })
                        .inspect(move |bytes| {
                            let bytes = bytes.as_ref().unwrap();
                            if bytes
                                .as_ref()
                                .windows(12)
                                .any(|window| window == b"data: [DONE]")
                            {
                                let mut locked_queue = running_queue.lock().unwrap();
                                let count = locked_queue.get_mut(&worker_url).unwrap();
                                *count = count.saturating_sub(1);
370
                                debug!("streaming is done!!")
371
372
373
                            }
                        }),
                )
374
375
376
377
        } else {
            HttpResponse::build(status)
                .insert_header((CONTENT_TYPE, HeaderValue::from_static("text/event-stream")))
                .streaming(res.bytes_stream().map_err(|_| {
378
                    actix_web::error::ErrorInternalServerError("Failed to read stream")
379
                }))
380
381
        }
    }
382
}