Skip to main content

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    /// [Condition expression] evaluated before each put (insert or upsert).
148    ///
149    /// When the condition is false, the record is skipped without failing the
150    /// connector. This option requires `transactional` [`write_mode`].
151    ///
152    /// The condition gates every value write, and the connector cannot tell a
153    /// replayed insert from a legitimate update: both arrive as puts. A guard
154    /// such as `attribute_not_exists(id)` therefore also suppresses updates to
155    /// existing keys, not just replayed duplicates. Choose the expression
156    /// accordingly.
157    ///
158    /// The connector does not currently support `ExpressionAttributeNames` or
159    /// `ExpressionAttributeValues`, so the expression cannot use placeholders.
160    ///
161    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
162    /// [`write_mode`]: Self::write_mode
163    #[serde(default)]
164    pub put_condition_expression: Option<String>,
165
166    /// [Condition expression] evaluated before each delete.
167    ///
168    /// When the condition is false, the delete is skipped without failing the
169    /// connector. This option requires `transactional` [`write_mode`]. The
170    /// expression cannot use `ExpressionAttributeNames` or
171    /// `ExpressionAttributeValues` placeholders.
172    ///
173    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
174    /// [`write_mode`]: Self::write_mode
175    #[serde(default)]
176    pub delete_condition_expression: Option<String>,
177}
178
179impl DynamoDBWriterConfig {
180    pub fn effective_batch_size(&self) -> usize {
181        self.batch_size
182            .unwrap_or_else(|| self.write_mode.max_batch_size())
183    }
184
185    pub fn validate(&self) -> Result<(), String> {
186        if self.table.trim().is_empty() {
187            return Err("table cannot be empty".to_string());
188        }
189        if self.table.len() < 3 || self.table.len() > 255 {
190            return Err(format!(
191                "table name '{}' is {} character(s); DynamoDB requires 3–255 characters",
192                self.table,
193                self.table.len()
194            ));
195        }
196        if !self
197            .table
198            .chars()
199            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
200        {
201            return Err(format!(
202                "table name '{}' contains invalid characters; DynamoDB requires [a-zA-Z0-9_.-]",
203                self.table
204            ));
205        }
206        if self.region.trim().is_empty() {
207            return Err("region cannot be empty".to_string());
208        }
209        if let Some(batch_size) = self.batch_size {
210            let max_batch_size = self.write_mode.max_batch_size();
211            if batch_size == 0 || batch_size > max_batch_size {
212                return Err(format!(
213                    "batch_size must be between 1 and {max_batch_size} for {:?} write mode",
214                    self.write_mode
215                ));
216            }
217        }
218        if self.threads == 0 {
219            return Err("threads must be at least 1".to_string());
220        }
221        if self.max_buffer_size_bytes == 0 {
222            return Err("max_buffer_size_bytes must be greater than 0".to_string());
223        }
224        if self.max_concurrent_requests == 0 {
225            return Err("max_concurrent_requests must be greater than 0".to_string());
226        }
227        match (&self.aws_access_key_id, &self.aws_secret_access_key) {
228            (Some(_), Some(_)) | (None, None) => {}
229            _ => {
230                return Err(
231                    "aws_access_key_id and aws_secret_access_key must be specified together"
232                        .to_string(),
233                );
234            }
235        }
236        for (field, expression) in [
237            ("put_condition_expression", &self.put_condition_expression),
238            (
239                "delete_condition_expression",
240                &self.delete_condition_expression,
241            ),
242        ] {
243            if let Some(expression) = expression {
244                if expression.trim().is_empty() {
245                    return Err(format!("{field} cannot be empty"));
246                }
247                if self.write_mode != DynamoDBWriteMode::Transactional {
248                    return Err(format!(
249                        "{field} requires the 'transactional' write mode; conditional writes \
250                         are not supported for 'batch' writes"
251                    ));
252                }
253            }
254        }
255        Ok(())
256    }
257}
258
259impl DynamoDBWriteMode {
260    pub fn max_batch_size(self) -> usize {
261        match self {
262            Self::Batch => 25,
263            Self::Transactional => 100,
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    fn config(write_mode: DynamoDBWriteMode, batch_size: Option<usize>) -> DynamoDBWriterConfig {
273        DynamoDBWriterConfig {
274            table: "test_table".to_string(),
275            region: "us-east-1".to_string(),
276            endpoint_url: None,
277            aws_access_key_id: None,
278            aws_secret_access_key: None,
279            batch_size,
280            write_mode,
281            max_buffer_size_bytes: 1024 * 1024,
282            max_concurrent_requests: 16,
283            threads: 1,
284            max_retries: Some(10u8),
285            put_condition_expression: None,
286            delete_condition_expression: None,
287        }
288    }
289
290    #[test]
291    fn default_batch_size_is_mode_specific() {
292        assert_eq!(
293            config(DynamoDBWriteMode::Batch, None).effective_batch_size(),
294            25
295        );
296        assert_eq!(
297            config(DynamoDBWriteMode::Transactional, None).effective_batch_size(),
298            100
299        );
300    }
301
302    #[test]
303    fn explicit_batch_size_is_validated_against_mode_limit() {
304        assert!(
305            config(DynamoDBWriteMode::Batch, Some(25))
306                .validate()
307                .is_ok()
308        );
309        assert!(
310            config(DynamoDBWriteMode::Batch, Some(26))
311                .validate()
312                .is_err()
313        );
314        assert!(
315            config(DynamoDBWriteMode::Transactional, Some(100))
316                .validate()
317                .is_ok()
318        );
319        assert!(
320            config(DynamoDBWriteMode::Transactional, Some(101))
321                .validate()
322                .is_err()
323        );
324    }
325
326    #[test]
327    fn table_name_validation() {
328        let base = config(DynamoDBWriteMode::Batch, None);
329
330        // too short
331        assert!(
332            DynamoDBWriterConfig {
333                table: "ab".to_string(),
334                ..base.clone()
335            }
336            .validate()
337            .is_err()
338        );
339        // minimum length
340        assert!(
341            DynamoDBWriterConfig {
342                table: "abc".to_string(),
343                ..base.clone()
344            }
345            .validate()
346            .is_ok()
347        );
348        // too long
349        assert!(
350            DynamoDBWriterConfig {
351                table: "a".repeat(256),
352                ..base.clone()
353            }
354            .validate()
355            .is_err()
356        );
357        // maximum length
358        assert!(
359            DynamoDBWriterConfig {
360                table: "a".repeat(255),
361                ..base.clone()
362            }
363            .validate()
364            .is_ok()
365        );
366        // invalid characters
367        assert!(
368            DynamoDBWriterConfig {
369                table: "my/table".to_string(),
370                ..base.clone()
371            }
372            .validate()
373            .is_err()
374        );
375        assert!(
376            DynamoDBWriterConfig {
377                table: "my table".to_string(),
378                ..base.clone()
379            }
380            .validate()
381            .is_err()
382        );
383        // valid characters
384        assert!(
385            DynamoDBWriterConfig {
386                table: "my.table-name_1".to_string(),
387                ..base.clone()
388            }
389            .validate()
390            .is_ok()
391        );
392    }
393
394    #[test]
395    fn condition_requires_transactional_write_mode() {
396        // A put condition in batch mode is rejected.
397        let batch = DynamoDBWriterConfig {
398            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
399            ..config(DynamoDBWriteMode::Batch, None)
400        };
401        assert!(batch.validate().is_err());
402
403        // The same condition is accepted in transactional mode.
404        let transactional = DynamoDBWriterConfig {
405            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
406            ..config(DynamoDBWriteMode::Transactional, None)
407        };
408        assert!(transactional.validate().is_ok());
409
410        // A delete condition in batch mode is rejected as well.
411        let batch_delete = DynamoDBWriterConfig {
412            delete_condition_expression: Some("attribute_exists(id)".to_string()),
413            ..config(DynamoDBWriteMode::Batch, None)
414        };
415        assert!(batch_delete.validate().is_err());
416    }
417
418    #[test]
419    fn blank_condition_is_rejected() {
420        let cfg = DynamoDBWriterConfig {
421            put_condition_expression: Some("   ".to_string()),
422            ..config(DynamoDBWriteMode::Transactional, None)
423        };
424        assert!(cfg.validate().is_err());
425    }
426
427    #[test]
428    fn null_max_retries_deserializes_as_unbounded() {
429        let json = r#"{"table":"t","region":"us-east-1","max_retries":null}"#;
430        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
431        assert_eq!(cfg.max_retries, None);
432    }
433
434    #[test]
435    fn omitted_max_retries_deserializes_as_default() {
436        let json = r#"{"table":"t","region":"us-east-1"}"#;
437        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
438        assert_eq!(cfg.max_retries, Some(10u8));
439    }
440}