File size: 38,907 Bytes
5a9e79d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java
@@ -725,6 +725,33 @@ public class ExecutionConfigOptions {
                             "Set whether to use the SQL/Table operators based on the asynchronous state api. "
                                     + "Default value is false.");
 
+    @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING)
+    public static final ConfigOption<Boolean> TABLE_EXEC_DELTA_JOIN_CACHE_ENABLED =
+            key("table.exec.delta-join.cache-enabled")
+                    .booleanType()
+                    .defaultValue(true)
+                    .withDescription(
+                            "Whether to enable the cache of delta join. If enabled, the delta join caches the "
+                                    + "records from remote dim table. Default is true.");
+
+    @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING)
+    public static final ConfigOption<Long> TABLE_EXEC_DELTA_JOIN_LEFT_CACHE_SIZE =
+            key("table.exec.delta-join.left.cache-size")
+                    .longType()
+                    .defaultValue(10000L)
+                    .withDescription(
+                            "The cache size used to cache the lookup results of the left table in delta join. "
+                                    + "This value must be positive when enabling cache. Default is 10000.");
+
+    @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING)
+    public static final ConfigOption<Long> TABLE_EXEC_DELTA_JOIN_RIGHT_CACHE_SIZE =
+            key("table.exec.delta-join.right.cache-size")
+                    .longType()
+                    .defaultValue(10000L)
+                    .withDescription(
+                            "The cache size used to cache the lookup results of the right table in delta join. "
+                                    + "This value must be positive when enabling cache. Default is 10000.");
+
     // ------------------------------------------------------------------------------------------
     // Enum option types
     // ------------------------------------------------------------------------------------------
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java
@@ -20,10 +20,12 @@
 
 import org.apache.flink.FlinkVersion;
 import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.api.java.tuple.Tuple2;
 import org.apache.flink.configuration.ReadableConfig;
 import org.apache.flink.streaming.api.functions.async.AsyncFunction;
 import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
 import org.apache.flink.streaming.api.transformations.TwoInputTransformation;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
 import org.apache.flink.table.catalog.DataTypeFactory;
 import org.apache.flink.table.data.RowData;
 import org.apache.flink.table.data.conversion.DataStructureConverter;
@@ -83,6 +85,7 @@
 import java.util.Map;
 import java.util.Optional;
 import java.util.stream.Collectors;
+import java.util.stream.IntStream;
 
 import static org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecDeltaJoin.DELTA_JOIN_TRANSFORMATION;
 import static org.apache.flink.table.planner.plan.utils.DeltaJoinUtil.getUnwrappedAsyncLookupFunction;
@@ -234,11 +237,17 @@ protected Transformation<RowData> translateToPlanInternal(
         RowDataKeySelector leftJoinKeySelector =
                 KeySelectorUtil.getRowDataSelector(
                         classLoader, leftJoinKeys, InternalTypeInfo.of(leftStreamType));
+        // currently, delta join only supports consuming INSERT-ONLY stream
+        RowDataKeySelector leftUpsertKeySelector =
+                getUpsertKeySelector(new int[0], leftStreamType, classLoader);
 
         // right side selector
         RowDataKeySelector rightJoinKeySelector =
                 KeySelectorUtil.getRowDataSelector(
                         classLoader, rightJoinKeys, InternalTypeInfo.of(rightStreamType));
+        // currently, delta join only supports consuming INSERT-ONLY stream
+        RowDataKeySelector rightUpsertKeySelector =
+                getUpsertKeySelector(new int[0], rightStreamType, classLoader);
 
         StreamOperatorFactory<RowData> operatorFactory =
                 createAsyncLookupDeltaJoin(
@@ -252,7 +261,9 @@ protected Transformation<RowData> translateToPlanInternal(
                         leftStreamType,
                         rightStreamType,
                         leftJoinKeySelector,
+                        leftUpsertKeySelector,
                         rightJoinKeySelector,
+                        rightUpsertKeySelector,
                         classLoader);
 
         final TwoInputTransformation<RowData, RowData, RowData> transform =
@@ -282,7 +293,9 @@ private StreamOperatorFactory<RowData> createAsyncLookupDeltaJoin(
             RowType leftStreamType,
             RowType rightStreamType,
             RowDataKeySelector leftJoinKeySelector,
+            RowDataKeySelector leftUpsertKeySelector,
             RowDataKeySelector rightJoinKeySelector,
+            RowDataKeySelector rightUpsertKeySelector,
             ClassLoader classLoader) {
 
         DataTypeFactory dataTypeFactory =
@@ -299,6 +312,10 @@ private StreamOperatorFactory<RowData> createAsyncLookupDeltaJoin(
                         leftStreamType,
                         rightStreamType,
                         leftLookupKeys,
+                        leftJoinKeySelector,
+                        leftUpsertKeySelector,
+                        rightJoinKeySelector,
+                        rightUpsertKeySelector,
                         false);
 
         AsyncDeltaJoinRunner rightLookupTableAsyncFunction =
@@ -312,15 +329,23 @@ private StreamOperatorFactory<RowData> createAsyncLookupDeltaJoin(
                         leftStreamType,
                         rightStreamType,
                         rightLookupKeys,
+                        leftJoinKeySelector,
+                        leftUpsertKeySelector,
+                        rightJoinKeySelector,
+                        rightUpsertKeySelector,
                         true);
 
+        Tuple2<Long, Long> leftRightCacheSize = getCacheSize(config);
+
         return new StreamingDeltaJoinOperatorFactory(
                 rightLookupTableAsyncFunction,
                 leftLookupTableAsyncFunction,
                 leftJoinKeySelector,
                 rightJoinKeySelector,
                 asyncLookupOptions.asyncTimeout,
                 asyncLookupOptions.asyncBufferCapacity,
+                leftRightCacheSize.f0,
+                leftRightCacheSize.f1,
                 leftStreamType,
                 rightStreamType);
     }
@@ -336,6 +361,10 @@ private AsyncDeltaJoinRunner createAsyncDeltaJoinRunner(
             RowType leftStreamSideType,
             RowType rightStreamSideType,
             Map<Integer, FunctionParam> lookupKeys,
+            RowDataKeySelector leftJoinKeySelector,
+            RowDataKeySelector leftUpsertKeySelector,
+            RowDataKeySelector rightJoinKeySelector,
+            RowDataKeySelector rightUpsertKeySelector,
             boolean treatRightAsLookupTable) {
         RelOptTable lookupTable = treatRightAsLookupTable ? rightTempTable : leftTempTable;
         RowType streamSideType = treatRightAsLookupTable ? leftStreamSideType : rightStreamSideType;
@@ -409,8 +438,13 @@ private AsyncDeltaJoinRunner createAsyncDeltaJoinRunner(
                 (DataStructureConverter<RowData, Object>) lookupSideFetcherConverter,
                 lookupSideGeneratedResultFuture,
                 InternalSerializers.create(lookupTableSourceRowType),
+                leftJoinKeySelector,
+                leftUpsertKeySelector,
+                rightJoinKeySelector,
+                rightUpsertKeySelector,
                 asyncLookupOptions.asyncBufferCapacity,
-                treatRightAsLookupTable);
+                treatRightAsLookupTable,
+                enableCache(config));
     }
 
     /**
@@ -449,4 +483,33 @@ public RexNode visitInputRef(RexInputRef inputRef) {
 
         return condition.accept(converter);
     }
+
+    private RowDataKeySelector getUpsertKeySelector(
+            int[] upsertKey, RowType rowType, ClassLoader classLoader) {
+        final int[] rightUpsertKeys;
+        if (upsertKey.length > 0) {
+            rightUpsertKeys = upsertKey;
+        } else {
+            rightUpsertKeys = IntStream.range(0, rowType.getFields().size()).toArray();
+        }
+        return KeySelectorUtil.getRowDataSelector(
+                classLoader, rightUpsertKeys, InternalTypeInfo.of(rowType));
+    }
+
+    private boolean enableCache(ReadableConfig config) {
+        return config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_CACHE_ENABLED);
+    }
+
+    /** Get the left cache size and right size. */
+    private Tuple2<Long, Long> getCacheSize(ReadableConfig config) {
+        long leftCacheSize =
+                config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_LEFT_CACHE_SIZE);
+        long rightCacheSize =
+                config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_RIGHT_CACHE_SIZE);
+        if ((leftCacheSize <= 0 || rightCacheSize <= 0) && enableCache(config)) {
+            throw new IllegalArgumentException(
+                    "Cache size in delta join must be positive when enabling cache.");
+        }
+        return Tuple2.of(leftCacheSize, rightCacheSize);
+    }
 }
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java
--- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java
@@ -36,13 +36,17 @@ public class StreamingDeltaJoinOperatorFactory extends AbstractStreamOperatorFac
                 YieldingOperatorFactory<RowData> {
 
     private final AsyncDeltaJoinRunner rightLookupTableAsyncFunction;
-    private final RowDataKeySelector rightJoinKeySelector;
     private final AsyncDeltaJoinRunner leftLookupTableAsyncFunction;
+
     private final RowDataKeySelector leftJoinKeySelector;
+    private final RowDataKeySelector rightJoinKeySelector;
 
     private final long timeout;
     private final int capacity;
 
+    private final long leftSideCacheSize;
+    private final long rightSideCacheSize;
+
     private final RowType leftStreamType;
     private final RowType rightStreamType;
 
@@ -53,6 +57,8 @@ public StreamingDeltaJoinOperatorFactory(
             RowDataKeySelector rightJoinKeySelector,
             long timeout,
             int capacity,
+            long leftSideCacheSize,
+            long rightSideCacheSize,
             RowType leftStreamType,
             RowType rightStreamType) {
         this.rightLookupTableAsyncFunction = rightLookupTableAsyncFunction;
@@ -61,6 +67,8 @@ public StreamingDeltaJoinOperatorFactory(
         this.rightJoinKeySelector = rightJoinKeySelector;
         this.timeout = timeout;
         this.capacity = capacity;
+        this.leftSideCacheSize = leftSideCacheSize;
+        this.rightSideCacheSize = rightSideCacheSize;
         this.leftStreamType = leftStreamType;
         this.rightStreamType = rightStreamType;
     }
@@ -79,6 +87,8 @@ public <T extends StreamOperator<RowData>> T createStreamOperator(
                         capacity,
                         processingTimeService,
                         mailboxExecutor,
+                        leftSideCacheSize,
+                        rightSideCacheSize,
                         leftStreamType,
                         rightStreamType);
         deltaJoinOperator.setup(
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java
--- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java
@@ -31,15 +31,21 @@
 import org.apache.flink.table.runtime.collector.TableFunctionResultFuture;
 import org.apache.flink.table.runtime.generated.GeneratedFunction;
 import org.apache.flink.table.runtime.generated.GeneratedResultFuture;
+import org.apache.flink.table.runtime.keyselector.RowDataKeySelector;
 import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.util.Preconditions;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.annotation.Nullable;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Optional;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
 
@@ -64,6 +70,22 @@ public class AsyncDeltaJoinRunner extends RichAsyncFunction<RowData, RowData> {
 
     private final boolean treatRightAsLookupTable;
 
+    private final boolean enableCache;
+
+    /** Selector to get join key from left input. */
+    private final RowDataKeySelector leftJoinKeySelector;
+
+    /** Selector to get upsert key from left input. */
+    private final RowDataKeySelector leftUpsertKeySelector;
+
+    /** Selector to get join key from right input. */
+    private final RowDataKeySelector rightJoinKeySelector;
+
+    /** Selector to get upsert key from right input. */
+    private final RowDataKeySelector rightUpsertKeySelector;
+
+    private transient DeltaJoinCache cache;
+
     /**
      * Buffers {@link ResultFuture} to avoid newInstance cost when processing elements every time.
      * We use {@link BlockingQueue} to make sure the head {@link ResultFuture}s are available.
@@ -85,14 +107,28 @@ public AsyncDeltaJoinRunner(
             DataStructureConverter<RowData, Object> fetcherConverter,
             GeneratedResultFuture<TableFunctionResultFuture<RowData>> generatedResultFuture,
             RowDataSerializer lookupSideRowSerializer,
+            RowDataKeySelector leftJoinKeySelector,
+            RowDataKeySelector leftUpsertKeySelector,
+            RowDataKeySelector rightJoinKeySelector,
+            RowDataKeySelector rightUpsertKeySelector,
             int asyncBufferCapacity,
-            boolean treatRightAsLookupTable) {
+            boolean treatRightAsLookupTable,
+            boolean enableCache) {
         this.generatedFetcher = generatedFetcher;
         this.fetcherConverter = fetcherConverter;
         this.generatedResultFuture = generatedResultFuture;
         this.lookupSideRowSerializer = lookupSideRowSerializer;
+        this.leftJoinKeySelector = leftJoinKeySelector;
+        this.leftUpsertKeySelector = leftUpsertKeySelector;
+        this.rightJoinKeySelector = rightJoinKeySelector;
+        this.rightUpsertKeySelector = rightUpsertKeySelector;
         this.asyncBufferCapacity = asyncBufferCapacity;
         this.treatRightAsLookupTable = treatRightAsLookupTable;
+        this.enableCache = enableCache;
+    }
+
+    public void setCache(DeltaJoinCache cache) {
+        this.cache = cache;
     }
 
     @Override
@@ -121,7 +157,11 @@ public void open(OpenContext openContext) throws Exception {
                             resultFutureBuffer,
                             createFetcherResultFuture(openContext),
                             fetcherConverter,
-                            treatRightAsLookupTable);
+                            treatRightAsLookupTable,
+                            leftUpsertKeySelector,
+                            rightUpsertKeySelector,
+                            enableCache,
+                            cache);
             // add will throw exception immediately if the queue is full which should never happen
             resultFutureBuffer.add(rf);
             allResultFutures.add(rf);
@@ -141,8 +181,27 @@ public void open(OpenContext openContext) throws Exception {
     public void asyncInvoke(RowData input, ResultFuture<RowData> resultFuture) throws Exception {
         JoinedRowResultFuture outResultFuture = resultFutureBuffer.take();
 
+        RowData streamJoinKey = null;
+        if (enableCache) {
+            if (treatRightAsLookupTable) {
+                streamJoinKey = leftJoinKeySelector.getKey(input);
+                cache.requestRightCache();
+            } else {
+                streamJoinKey = rightJoinKeySelector.getKey(input);
+                cache.requestLeftCache();
+            }
+        }
+
         // the input row is copied when object reuse in StreamDeltaJoinOperator
-        outResultFuture.reset(input, resultFuture);
+        outResultFuture.reset(streamJoinKey, input, resultFuture);
+
+        if (enableCache) {
+            Optional<Collection<Object>> dataFromCache = tryGetDataFromCache(streamJoinKey);
+            if (dataFromCache.isPresent()) {
+                outResultFuture.complete(dataFromCache.get());
+                return;
+            }
+        }
 
         long startTime = System.currentTimeMillis();
         // fetcher has copied the input field when object reuse is enabled
@@ -177,6 +236,30 @@ public AsyncFunction<RowData, Object> getFetcher() {
         return fetcher;
     }
 
+    @VisibleForTesting
+    public DeltaJoinCache getCache() {
+        return cache;
+    }
+
+    private Optional<Collection<Object>> tryGetDataFromCache(RowData joinKey) {
+        Preconditions.checkState(enableCache);
+
+        if (treatRightAsLookupTable) {
+            LinkedHashMap<RowData, Object> rightRows = cache.getData(joinKey, true);
+            if (rightRows != null) {
+                cache.hitRightCache();
+                return Optional.of(rightRows.values());
+            }
+        } else {
+            LinkedHashMap<RowData, Object> leftRows = cache.getData(joinKey, false);
+            if (leftRows != null) {
+                cache.hitLeftCache();
+                return Optional.of(leftRows.values());
+            }
+        }
+        return Optional.empty();
+    }
+
     /**
      * The {@link JoinedRowResultFuture} is used to combine left {@link RowData} and right {@link
      * RowData} into {@link JoinedRowData}.
@@ -191,26 +274,45 @@ public static final class JoinedRowResultFuture implements ResultFuture<Object>
         private final TableFunctionResultFuture<RowData> joinConditionResultFuture;
         private final DataStructureConverter<RowData, Object> resultConverter;
 
+        private final boolean enableCache;
+        private final DeltaJoinCache cache;
+
         private final DelegateResultFuture delegate;
         private final boolean treatRightAsLookupTable;
 
+        private final RowDataKeySelector leftUpsertKeySelector;
+        private final RowDataKeySelector rightUpsertKeySelector;
+
+        private @Nullable RowData streamJoinKey;
         private RowData streamRow;
         private ResultFuture<RowData> realOutput;
 
         private JoinedRowResultFuture(
                 BlockingQueue<JoinedRowResultFuture> resultFutureBuffer,
                 TableFunctionResultFuture<RowData> joinConditionResultFuture,
                 DataStructureConverter<RowData, Object> resultConverter,
-                boolean treatRightAsLookupTable) {
+                boolean treatRightAsLookupTable,
+                RowDataKeySelector leftUpsertKeySelector,
+                RowDataKeySelector rightUpsertKeySelector,
+                boolean enableCache,
+                DeltaJoinCache cache) {
             this.resultFutureBuffer = resultFutureBuffer;
             this.joinConditionResultFuture = joinConditionResultFuture;
             this.resultConverter = resultConverter;
+            this.enableCache = enableCache;
+            this.cache = cache;
             this.delegate = new DelegateResultFuture();
             this.treatRightAsLookupTable = treatRightAsLookupTable;
+            this.leftUpsertKeySelector = leftUpsertKeySelector;
+            this.rightUpsertKeySelector = rightUpsertKeySelector;
         }
 
-        public void reset(RowData row, ResultFuture<RowData> realOutput) {
+        public void reset(
+                @Nullable RowData joinKey, RowData row, ResultFuture<RowData> realOutput) {
+            Preconditions.checkState(
+                    (enableCache && joinKey != null) || (!enableCache && joinKey == null));
             this.realOutput = realOutput;
+            this.streamJoinKey = joinKey;
             this.streamRow = row;
             joinConditionResultFuture.setInput(row);
             joinConditionResultFuture.setResultFuture(delegate);
@@ -219,6 +321,19 @@ public void reset(RowData row, ResultFuture<RowData> realOutput) {
 
         @Override
         public void complete(Collection<Object> result) {
+            if (result == null) {
+                result = Collections.emptyList();
+            }
+
+            // now we have received the rows from the lookup table, try to set them to the cache
+            try {
+                updateCacheIfNecessary(result);
+            } catch (Throwable t) {
+                LOG.info("Failed to update the cache", t);
+                completeExceptionally(t);
+                return;
+            }
+
             Collection<RowData> rowDataCollection = convertToInternalData(result);
             // call condition collector first,
             // the filtered result will be routed to the delegateCollector
@@ -273,6 +388,61 @@ public void close() throws Exception {
             joinConditionResultFuture.close();
         }
 
+        private void updateCacheIfNecessary(Collection<Object> lookupRows) throws Exception {
+            if (!enableCache) {
+                return;
+            }
+
+            // 1. build the cache in lookup side if not exists
+            // 2. update the cache in stream side if exists
+            if (treatRightAsLookupTable) {
+                if (cache.getData(streamJoinKey, true) == null) {
+                    cache.buildCache(streamJoinKey, buildMapWithUkAsKeys(lookupRows, true), true);
+                }
+
+                LinkedHashMap<RowData, Object> leftCacheData = cache.getData(streamJoinKey, false);
+                if (leftCacheData != null) {
+                    RowData uk = leftUpsertKeySelector.getKey(streamRow);
+                    cache.upsertCache(streamJoinKey, uk, streamRow, false);
+                }
+            } else {
+                if (cache.getData(streamJoinKey, false) == null) {
+                    cache.buildCache(streamJoinKey, buildMapWithUkAsKeys(lookupRows, false), false);
+                }
+
+                LinkedHashMap<RowData, Object> rightCacheData = cache.getData(streamJoinKey, true);
+                if (rightCacheData != null) {
+                    RowData uk = rightUpsertKeySelector.getKey(streamRow);
+                    cache.upsertCache(streamJoinKey, uk, streamRow, true);
+                }
+            }
+        }
+
+        private LinkedHashMap<RowData, Object> buildMapWithUkAsKeys(
+                Collection<Object> lookupRows, boolean treatRightAsLookupTable) throws Exception {
+            LinkedHashMap<RowData, Object> map = new LinkedHashMap<>();
+            for (Object lookupRow : lookupRows) {
+                RowData rowData = convertToInternalData(lookupRow);
+                RowData uk;
+                if (treatRightAsLookupTable) {
+                    uk = rightUpsertKeySelector.getKey(rowData);
+                    map.put(uk, lookupRow);
+                } else {
+                    uk = leftUpsertKeySelector.getKey(rowData);
+                    map.put(uk, lookupRow);
+                }
+            }
+            return map;
+        }
+
+        private RowData convertToInternalData(Object data) {
+            if (resultConverter.isIdentityConversion()) {
+                return (RowData) data;
+            } else {
+                return resultConverter.toInternal(data);
+            }
+        }
+
         @SuppressWarnings({"unchecked", "rawtypes"})
         private Collection<RowData> convertToInternalData(Collection<Object> data) {
             if (resultConverter.isIdentityConversion()) {
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.operators.join.deltajoin;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.MetricGroup;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.flink.shaded.guava33.com.google.common.cache.Cache;
+import org.apache.flink.shaded.guava33.com.google.common.cache.CacheBuilder;
+import org.apache.flink.shaded.guava33.com.google.common.cache.RemovalListener;
+import org.apache.flink.shaded.guava33.com.google.common.cache.RemovalNotification;
+
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.util.LinkedHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Cache for both sides in delta join.
+ *
+ * <p>Note: This cache is not thread-safe although its inner {@link Cache} is thread-safe.
+ */
+@NotThreadSafe
+public class DeltaJoinCache {
+
+    private static final String LEFT_CACHE_METRIC_PREFIX = "deltaJoin.leftCache.";
+    private static final String RIGHT_CACHE_METRIC_PREFIX = "deltaJoin.rightCache.";
+
+    private static final String METRIC_HIT_RATE = "hitRate";
+    private static final String METRIC_REQUEST_COUNT = "requestCount";
+    private static final String METRIC_HIT_COUNT = "hitCount";
+    private static final String METRIC_KEY_SIZE = "keySize";
+    private static final String METRIC_TOTAL_NON_EMPTY_VALUE_SIZE = "totalNonEmptyValues";
+
+    // use LinkedHashMap to keep order
+    private final Cache<RowData, LinkedHashMap<RowData, Object>> leftCache;
+    private final Cache<RowData, LinkedHashMap<RowData, Object>> rightCache;
+
+    // metrics
+    private final AtomicLong leftTotalSize = new AtomicLong(0L);
+    private final AtomicLong rightTotalSize = new AtomicLong(0L);
+    private final AtomicLong leftHitCount = new AtomicLong(0L);
+    private final AtomicLong leftRequestCount = new AtomicLong(0L);
+    private final AtomicLong rightHitCount = new AtomicLong(0L);
+    private final AtomicLong rightRequestCount = new AtomicLong(0L);
+
+    public DeltaJoinCache(long leftCacheMaxSize, long rightCacheMaxSize) {
+        this.leftCache =
+                CacheBuilder.newBuilder()
+                        .maximumSize(leftCacheMaxSize)
+                        .removalListener(new DeltaJoinCacheRemovalListener(true))
+                        .build();
+        this.rightCache =
+                CacheBuilder.newBuilder()
+                        .maximumSize(rightCacheMaxSize)
+                        .removalListener(new DeltaJoinCacheRemovalListener(false))
+                        .build();
+    }
+
+    public void registerMetrics(MetricGroup metricGroup) {
+        // left cache metric
+        metricGroup.<Double, Gauge<Double>>gauge(
+                LEFT_CACHE_METRIC_PREFIX + METRIC_HIT_RATE,
+                () ->
+                        leftRequestCount.get() == 0
+                                ? 0.0
+                                : Long.valueOf(leftHitCount.get()).doubleValue()
+                                        / leftRequestCount.get());
+        metricGroup.<Long, Gauge<Long>>gauge(
+                LEFT_CACHE_METRIC_PREFIX + METRIC_REQUEST_COUNT, rightRequestCount::get);
+        metricGroup.<Long, Gauge<Long>>gauge(
+                LEFT_CACHE_METRIC_PREFIX + METRIC_HIT_COUNT, leftHitCount::get);
+        metricGroup.<Long, Gauge<Long>>gauge(
+                LEFT_CACHE_METRIC_PREFIX + METRIC_KEY_SIZE, leftCache::size);
+
+        metricGroup.<Long, Gauge<Long>>gauge(
+                LEFT_CACHE_METRIC_PREFIX + METRIC_TOTAL_NON_EMPTY_VALUE_SIZE, leftTotalSize::get);
+
+        // right cache metric
+        metricGroup.<Double, Gauge<Double>>gauge(
+                RIGHT_CACHE_METRIC_PREFIX + METRIC_HIT_RATE,
+                () ->
+                        rightRequestCount.get() == 0
+                                ? 0.0
+                                : Long.valueOf(rightHitCount.get()).doubleValue()
+                                        / rightRequestCount.get());
+        metricGroup.<Long, Gauge<Long>>gauge(
+                RIGHT_CACHE_METRIC_PREFIX + METRIC_REQUEST_COUNT, rightRequestCount::get);
+        metricGroup.<Long, Gauge<Long>>gauge(
+                RIGHT_CACHE_METRIC_PREFIX + METRIC_HIT_COUNT, rightHitCount::get);
+        metricGroup.<Long, Gauge<Long>>gauge(
+                RIGHT_CACHE_METRIC_PREFIX + METRIC_KEY_SIZE, rightCache::size);
+        metricGroup.<Long, Gauge<Long>>gauge(
+                RIGHT_CACHE_METRIC_PREFIX + METRIC_TOTAL_NON_EMPTY_VALUE_SIZE, rightTotalSize::get);
+    }
+
+    @Nullable
+    public LinkedHashMap<RowData, Object> getData(RowData key, boolean requestRightCache) {
+        return requestRightCache ? rightCache.getIfPresent(key) : leftCache.getIfPresent(key);
+    }
+
+    public void buildCache(
+            RowData key, LinkedHashMap<RowData, Object> ukDataMap, boolean buildRightCache) {
+        Preconditions.checkState(getData(key, buildRightCache) == null);
+        if (buildRightCache) {
+            rightCache.put(key, ukDataMap);
+            rightTotalSize.addAndGet(ukDataMap.size());
+        } else {
+            leftCache.put(key, ukDataMap);
+            leftTotalSize.addAndGet(ukDataMap.size());
+        }
+    }
+
+    public void upsertCache(RowData key, RowData uk, Object data, boolean upsertRightCache) {
+        if (upsertRightCache) {
+            upsert(rightCache, key, uk, data, rightTotalSize);
+        } else {
+            upsert(leftCache, key, uk, data, leftTotalSize);
+        }
+    }
+
+    private void upsert(
+            Cache<RowData, LinkedHashMap<RowData, Object>> cache,
+            RowData key,
+            RowData uk,
+            Object data,
+            AtomicLong cacheTotalSize) {
+        cache.asMap()
+                .computeIfPresent(
+                        key,
+                        (k, v) -> {
+                            Object oldData = v.put(uk, data);
+                            if (oldData == null) {
+                                cacheTotalSize.incrementAndGet();
+                            }
+                            return v;
+                        });
+    }
+
+    public void requestLeftCache() {
+        leftRequestCount.incrementAndGet();
+    }
+
+    public void requestRightCache() {
+        rightRequestCount.incrementAndGet();
+    }
+
+    public void hitLeftCache() {
+        leftHitCount.incrementAndGet();
+    }
+
+    public void hitRightCache() {
+        rightHitCount.incrementAndGet();
+    }
+
+    private class DeltaJoinCacheRemovalListener
+            implements RemovalListener<RowData, LinkedHashMap<RowData, Object>> {
+
+        private final boolean isLeftCache;
+
+        public DeltaJoinCacheRemovalListener(boolean isLeftCache) {
+            this.isLeftCache = isLeftCache;
+        }
+
+        @Override
+        public void onRemoval(
+                RemovalNotification<RowData, LinkedHashMap<RowData, Object>> removalNotification) {
+            if (removalNotification.getValue() == null) {
+                return;
+            }
+
+            if (isLeftCache) {
+                leftTotalSize.addAndGet(-removalNotification.getValue().size());
+            } else {
+                rightTotalSize.addAndGet(-removalNotification.getValue().size());
+            }
+        }
+    }
+
+    // ===== visible for test =====
+
+    @VisibleForTesting
+    public Cache<RowData, LinkedHashMap<RowData, Object>> getLeftCache() {
+        return leftCache;
+    }
+
+    @VisibleForTesting
+    public Cache<RowData, LinkedHashMap<RowData, Object>> getRightCache() {
+        return rightCache;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getLeftTotalSize() {
+        return leftTotalSize;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getRightTotalSize() {
+        return rightTotalSize;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getLeftHitCount() {
+        return leftHitCount;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getLeftRequestCount() {
+        return leftRequestCount;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getRightHitCount() {
+        return rightHitCount;
+    }
+
+    @VisibleForTesting
+    public AtomicLong getRightRequestCount() {
+        return rightRequestCount;
+    }
+}
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java
--- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java
@@ -99,7 +99,7 @@ public class StreamingDeltaJoinOperator
 
     private static final String METRIC_DELTA_JOIN_OP_TOTAL_IN_FLIGHT_NUM =
             "deltaJoinOpTotalInFlightNum";
-    private static final String METRIC_DELTA_JOIN_ASYNC_IO_TIME = "deltaJoinAsyncIoTime";
+    private static final String METRIC_DELTA_JOIN_ASYNC_IO_TIME = "deltaJoinAsyncIOTime";
 
     private final StreamRecord<RowData> leftEmptyStreamRecord;
     private final StreamRecord<RowData> rightEmptyStreamRecord;
@@ -116,6 +116,10 @@ public class StreamingDeltaJoinOperator
     /** Max number of inflight invocation. */
     private final int capacity;
 
+    private final long leftSideCacheSize;
+
+    private final long rightSideCacheSize;
+
     private transient boolean needDeepCopy;
 
     /** {@link TypeSerializer} for left side inputs while making snapshots. */
@@ -138,6 +142,8 @@ public class StreamingDeltaJoinOperator
     private transient TableAsyncExecutionController<RowData, RowData, RowData>
             asyncExecutionController;
 
+    private transient DeltaJoinCache cache;
+
     /** Mailbox executor used to yield while waiting for buffers to empty. */
     private final transient MailboxExecutor mailboxExecutor;
 
@@ -172,6 +178,8 @@ public StreamingDeltaJoinOperator(
             int capacity,
             ProcessingTimeService processingTimeService,
             MailboxExecutor mailboxExecutor,
+            long leftSideCacheSize,
+            long rightSideCacheSize,
             RowType leftStreamType,
             RowType rightStreamType) {
         // rightLookupTableAsyncFunction is an udx used for left records
@@ -184,6 +192,8 @@ public StreamingDeltaJoinOperator(
         this.processingTimeService = checkNotNull(processingTimeService);
         this.mailboxExecutor = mailboxExecutor;
         this.isInputEnded = new boolean[2];
+        this.leftSideCacheSize = leftSideCacheSize;
+        this.rightSideCacheSize = rightSideCacheSize;
         this.leftEmptyStreamRecord =
                 new StreamRecord<>(new GenericRowData(leftStreamType.getFieldCount()));
         this.rightEmptyStreamRecord =
@@ -224,6 +234,11 @@ public void setup(
                                     isLeft(inputIndex) ? leftJoinKeySelector : rightJoinKeySelector;
                             return keySelector.getKey(record.getValue());
                         });
+
+        this.cache = new DeltaJoinCache(leftSideCacheSize, rightSideCacheSize);
+
+        leftTriggeredUserFunction.setCache(cache);
+        rightTriggeredUserFunction.setCache(cache);
     }
 
     @Override
@@ -275,6 +290,9 @@ public void open() throws Exception {
         getRuntimeContext()
                 .getMetricGroup()
                 .gauge(METRIC_DELTA_JOIN_ASYNC_IO_TIME, asyncIOTime::get);
+        // 3. cache metric
+        cache.registerMetrics(getRuntimeContext().getMetricGroup());
+
         // asyncBufferCapacity + 1 as the queue size in order to avoid
         // blocking on the queue when taking a collector.
         this.resultHandlerBuffer = new ArrayBlockingQueue<>(capacity + 1);