Skip to main content

feldera_types/transport/
dynamodb.rs

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