feldera_types/transport/dynamodb.rs
1use serde::{Deserialize, Serialize};
2use utoipa::ToSchema;
3
4/// Connectors by default start with 1 worker thread.
5/// Increasing the number of threads helps scale the encoding process; however, for
6/// DynamoDB, encoding is often not the bottleneck, writing to DynamoDB is.
7fn default_threads() -> usize {
8 1
9}
10
11/// Ten attempts with the ~13s backoff ceiling retries for roughly two minutes:
12/// enough to ride out transient throttling, bounded enough not to stall the
13/// pipeline forever. Set `max_retries` to `null` for unbounded.
14fn default_max_retries() -> Option<u8> {
15 Some(10)
16}
17
18fn default_max_buffer_size_bytes() -> usize {
19 1024 * 1024
20}
21
22/// Number of concurrent requests made to DynamoDB at any time.
23/// Increasing this may improve the throughput, but may also cause
24/// throttling and increase retries.
25///
26/// 64 concurrent requests mean at any time, we submit a maximum of:
27/// - 64 * 25 Batch items
28/// - 64 * 100 Transactional items
29fn default_max_concurrent_requests() -> usize {
30 64
31}
32
33/// Batch mode allows for higher throughput than transactional mode.
34fn default_write_mode() -> DynamoDBWriteMode {
35 DynamoDBWriteMode::Batch
36}
37
38/// DynamoDB write API used by the output connector.
39#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
40#[serde(rename_all = "snake_case")]
41pub enum DynamoDBWriteMode {
42 /// Use DynamoDB [`BatchWriteItem`].
43 ///
44 /// This is the high-throughput path. Each request writes up to 25 items,
45 /// and each item costs one write capacity unit (WCU). Writes are flushed at
46 /// batch end, but DynamoDB does not make the whole batch atomic: some items
47 /// in a request may succeed while others fail (and are retried).
48 ///
49 /// [`BatchWriteItem`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
50 Batch,
51
52 /// Use DynamoDB [`TransactWriteItems`].
53 ///
54 /// This provides atomicity for each transaction chunk: either all items in
55 /// the request are written or none are. It is substantially slower than
56 /// `Batch` and is limited to 100 writes per request.
57 ///
58 /// [`TransactWriteItems`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html
59 Transactional,
60}
61
62/// DynamoDB output connector configuration.
63#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
64pub struct DynamoDBWriterConfig {
65 /// Name of the DynamoDB table to write to.
66 pub table: String,
67
68 /// AWS region.
69 pub region: String,
70
71 /// Optional endpoint URL, for example when using a local
72 /// DynamoDB-compatible service.
73 pub endpoint_url: Option<String>,
74
75 /// AWS access key ID.
76 ///
77 /// If both `aws_access_key_id` and `aws_secret_access_key` are specified,
78 /// the connector uses these static credentials. Otherwise it uses the
79 /// default AWS credential provider chain, including IAM Roles for Service
80 /// Accounts (IRSA) in EKS.
81 ///
82 /// Static credentials are treated as long-lived IAM keys: no session token
83 /// is sent, so STS-issued temporary credentials are not supported via these
84 /// fields. To use temporary credentials, rely on the default provider chain
85 /// instead (leave these unset).
86 pub aws_access_key_id: Option<String>,
87
88 /// AWS secret access key.
89 pub aws_secret_access_key: Option<String>,
90
91 /// Maximum number of write requests in one DynamoDB write call.
92 ///
93 /// DynamoDB supports at most 100 for `TransactWriteItems` and at most 25
94 /// for `BatchWriteItem`. If omitted, the connector uses the maximum for
95 /// the selected `write_mode`.
96 #[serde(default)]
97 pub batch_size: Option<usize>,
98
99 /// Write API to use when flushing records at batch end.
100 ///
101 /// The default is `batch`, where each worker bulk-writes its own split
102 /// using DynamoDB `BatchWriteItem`.
103 #[serde(default = "default_write_mode")]
104 #[schema(default = default_write_mode)]
105 pub write_mode: DynamoDBWriteMode,
106
107 /// Maximum number of bytes buffered by each worker before flushing writes.
108 ///
109 /// This is an approximate size based on encoded DynamoDB attributes.
110 #[serde(default = "default_max_buffer_size_bytes")]
111 #[schema(default = default_max_buffer_size_bytes)]
112 pub max_buffer_size_bytes: usize,
113
114 /// Maximum number of DynamoDB write requests in flight per worker thread.
115 ///
116 /// The total in-flight request count across the connector is
117 /// `threads × max_concurrent_requests`. Size this accordingly when
118 /// tuning against a provisioned-throughput table to avoid excessive
119 /// throttling.
120 #[serde(default = "default_max_concurrent_requests")]
121 #[schema(default = default_max_concurrent_requests)]
122 pub max_concurrent_requests: usize,
123
124 /// Number of worker threads used to encode and write disjoint key ranges.
125 #[serde(default = "default_threads")]
126 #[schema(default = default_threads)]
127 pub threads: usize,
128
129 /// Maximum number of retries for a failed or partially-applied DynamoDB write chunk.
130 ///
131 /// For `batch` writes, `BatchWriteItem` may return some items as "unprocessed" in a
132 /// successful 200 response; those are re-submitted and counted as retries. For
133 /// `transactional` writes, a failed `TransactWriteItems` call is retried in full.
134 ///
135 /// Transient errors (throttling, network failures) are first handled transparently by the
136 /// AWS SDK. Only attempts that reach this connector's retry loop count against this limit.
137 /// Each retry waits longer than the previous one (exponential backoff), up to a ceiling
138 /// of roughly 13 seconds.
139 ///
140 /// Set to `null` to retry indefinitely. After the backoff ceiling is reached the connector
141 /// keeps retrying at that interval, providing backpressure until DynamoDB recovers.
142 /// Defaults to `10`.
143 #[serde(default = "default_max_retries")]
144 #[schema(default = default_max_retries)]
145 pub max_retries: Option<u8>,
146}
147
148impl DynamoDBWriterConfig {
149 pub fn effective_batch_size(&self) -> usize {
150 self.batch_size
151 .unwrap_or_else(|| self.write_mode.max_batch_size())
152 }
153
154 pub fn validate(&self) -> Result<(), String> {
155 if self.table.trim().is_empty() {
156 return Err("table cannot be empty".to_string());
157 }
158 if self.table.len() < 3 || self.table.len() > 255 {
159 return Err(format!(
160 "table name '{}' is {} character(s); DynamoDB requires 3–255 characters",
161 self.table,
162 self.table.len()
163 ));
164 }
165 if !self
166 .table
167 .chars()
168 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
169 {
170 return Err(format!(
171 "table name '{}' contains invalid characters; DynamoDB requires [a-zA-Z0-9_.-]",
172 self.table
173 ));
174 }
175 if self.region.trim().is_empty() {
176 return Err("region cannot be empty".to_string());
177 }
178 if let Some(batch_size) = self.batch_size {
179 let max_batch_size = self.write_mode.max_batch_size();
180 if batch_size == 0 || batch_size > max_batch_size {
181 return Err(format!(
182 "batch_size must be between 1 and {max_batch_size} for {:?} write mode",
183 self.write_mode
184 ));
185 }
186 }
187 if self.threads == 0 {
188 return Err("threads must be at least 1".to_string());
189 }
190 if self.max_buffer_size_bytes == 0 {
191 return Err("max_buffer_size_bytes must be greater than 0".to_string());
192 }
193 if self.max_concurrent_requests == 0 {
194 return Err("max_concurrent_requests must be greater than 0".to_string());
195 }
196 match (&self.aws_access_key_id, &self.aws_secret_access_key) {
197 (Some(_), Some(_)) | (None, None) => {}
198 _ => {
199 return Err(
200 "aws_access_key_id and aws_secret_access_key must be specified together"
201 .to_string(),
202 );
203 }
204 }
205 Ok(())
206 }
207}
208
209impl DynamoDBWriteMode {
210 pub fn max_batch_size(self) -> usize {
211 match self {
212 Self::Batch => 25,
213 Self::Transactional => 100,
214 }
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn config(write_mode: DynamoDBWriteMode, batch_size: Option<usize>) -> DynamoDBWriterConfig {
223 DynamoDBWriterConfig {
224 table: "test_table".to_string(),
225 region: "us-east-1".to_string(),
226 endpoint_url: None,
227 aws_access_key_id: None,
228 aws_secret_access_key: None,
229 batch_size,
230 write_mode,
231 max_buffer_size_bytes: 1024 * 1024,
232 max_concurrent_requests: 16,
233 threads: 1,
234 max_retries: Some(10u8),
235 }
236 }
237
238 #[test]
239 fn default_batch_size_is_mode_specific() {
240 assert_eq!(
241 config(DynamoDBWriteMode::Batch, None).effective_batch_size(),
242 25
243 );
244 assert_eq!(
245 config(DynamoDBWriteMode::Transactional, None).effective_batch_size(),
246 100
247 );
248 }
249
250 #[test]
251 fn explicit_batch_size_is_validated_against_mode_limit() {
252 assert!(
253 config(DynamoDBWriteMode::Batch, Some(25))
254 .validate()
255 .is_ok()
256 );
257 assert!(
258 config(DynamoDBWriteMode::Batch, Some(26))
259 .validate()
260 .is_err()
261 );
262 assert!(
263 config(DynamoDBWriteMode::Transactional, Some(100))
264 .validate()
265 .is_ok()
266 );
267 assert!(
268 config(DynamoDBWriteMode::Transactional, Some(101))
269 .validate()
270 .is_err()
271 );
272 }
273
274 #[test]
275 fn table_name_validation() {
276 let base = config(DynamoDBWriteMode::Batch, None);
277
278 // too short
279 assert!(
280 DynamoDBWriterConfig {
281 table: "ab".to_string(),
282 ..base.clone()
283 }
284 .validate()
285 .is_err()
286 );
287 // minimum length
288 assert!(
289 DynamoDBWriterConfig {
290 table: "abc".to_string(),
291 ..base.clone()
292 }
293 .validate()
294 .is_ok()
295 );
296 // too long
297 assert!(
298 DynamoDBWriterConfig {
299 table: "a".repeat(256),
300 ..base.clone()
301 }
302 .validate()
303 .is_err()
304 );
305 // maximum length
306 assert!(
307 DynamoDBWriterConfig {
308 table: "a".repeat(255),
309 ..base.clone()
310 }
311 .validate()
312 .is_ok()
313 );
314 // invalid characters
315 assert!(
316 DynamoDBWriterConfig {
317 table: "my/table".to_string(),
318 ..base.clone()
319 }
320 .validate()
321 .is_err()
322 );
323 assert!(
324 DynamoDBWriterConfig {
325 table: "my table".to_string(),
326 ..base.clone()
327 }
328 .validate()
329 .is_err()
330 );
331 // valid characters
332 assert!(
333 DynamoDBWriterConfig {
334 table: "my.table-name_1".to_string(),
335 ..base.clone()
336 }
337 .validate()
338 .is_ok()
339 );
340 }
341
342 #[test]
343 fn null_max_retries_deserializes_as_unbounded() {
344 let json = r#"{"table":"t","region":"us-east-1","max_retries":null}"#;
345 let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
346 assert_eq!(cfg.max_retries, None);
347 }
348
349 #[test]
350 fn omitted_max_retries_deserializes_as_default() {
351 let json = r#"{"table":"t","region":"us-east-1"}"#;
352 let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
353 assert_eq!(cfg.max_retries, Some(10u8));
354 }
355}