Slide 1

Slide 1 text

Reactive DOs and DONTs Sergei Egorov, Pivotal @bsideup

Slide 2

Slide 2 text

• Staff Engineer at Pivotal, Project Reactor team • Oracle Groundbreakers Ambassador • Berlin Spring User Group co-organizer • Testcontainers co-maintainer About me @bsideup

Slide 3

Slide 3 text

My first experience with reactive programming was like…

Slide 4

Slide 4 text

@bsideup

Slide 5

Slide 5 text

@bsideup

Slide 6

Slide 6 text

1 week later…

Slide 7

Slide 7 text

I agree with Heinrich Apfelmus that the essence of functional reactive programming is to specify the dynamic behavior of a value completely at the time of declaration. “Reactive Sir” @bsideup

Slide 8

Slide 8 text

1 week of production later…

Slide 9

Slide 9 text

@bsideup

Slide 10

Slide 10 text

So I went to the Gods…

Slide 11

Slide 11 text

Stephane @smaldini Maldini, Project Reactor’s team lead @bsideup Ex-

Slide 12

Slide 12 text

He was my manager, lol Stephane @smaldini Maldini, Project Reactor’s team lead @bsideup Ex-

Slide 13

Slide 13 text

Stephane @smaldini Maldini, Project Reactor’s team lead @bsideup Ex-

Slide 14

Slide 14 text

The Reactive Lord has given unto you these fifteen…

Slide 15

Slide 15 text

oy…

Slide 16

Slide 16 text

Ten! Ten commandments, for all to obey.

Slide 17

Slide 17 text

Learn functional programming DO @bsideup

Slide 18

Slide 18 text

@bsideup Haskell?

Slide 19

Slide 19 text

@bsideup Haskell?

Slide 20

Slide 20 text

@bsideup https://twitter.com/mariofusco/status/571999216039542784

Slide 21

Slide 21 text

Lazy evaluation

Slide 22

Slide 22 text

Mono.fromRunnable() @bsideup

Slide 23

Slide 23 text

Mono.fromRunnable() My code @bsideup

Slide 24

Slide 24 text

Mono.fromRunnable() My code My code @bsideup

Slide 25

Slide 25 text

Mono.fromRunnable() My code My code My code Work! @bsideup

Slide 26

Slide 26 text

Mono.fromRunnable().subscribe() @bsideup

Slide 27

Slide 27 text

An ideal app subscribes only once @bsideup

Slide 28

Slide 28 text

Immutability

Slide 29

Slide 29 text

Quiz static void addLogging(Flux flux) { flux.doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... Flux items = getFlux(); addLogging(items); items.subscribe(); @bsideup

Slide 30

Slide 30 text

Quiz static void addLogging(Flux flux) { flux.doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... Flux items = getFlux(); addLogging(items); items.subscribe(); 1. Will print both items and errors @bsideup

Slide 31

Slide 31 text

Quiz static void addLogging(Flux flux) { flux.doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... Flux items = getFlux(); addLogging(items); items.subscribe(); 1. Will print both items and errors 2. Will only print items, not errors @bsideup

Slide 32

Slide 32 text

Quiz static void addLogging(Flux flux) { flux.doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... Flux items = getFlux(); addLogging(items); items.subscribe(); 1. Will print both items and errors 2. Will only print items, not errors 3. Will not print anything @bsideup

Slide 33

Slide 33 text

Quiz static void addLogging(Flux flux) { flux.doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... Flux items = getFlux(); addLogging(items); items.subscribe(); 1. Will print both items and errors 2. Will only print items, not errors 3. Will not print anything @bsideup

Slide 34

Slide 34 text

public Mono map(Function super T, ? extends R> mapper) { return new MonoMap<>(this, mapper); } Immutability of reactive operators @bsideup Mono.just("Hello") .map(it -> it + " World!") .map(String::length)

Slide 35

Slide 35 text

public Mono map(Function super T, ? extends R> mapper) { return new MonoMap<>(this, mapper); } Immutability of reactive operators @bsideup Mono.just("Hello") .map(it -> it + " World!") .map(String::length)

Slide 36

Slide 36 text

static Flux addLogging(Flux flux) { return flux .doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... getFlux() .transform(flux -> addLogging(flux)) .subscribe(); @bsideup Always return…

Slide 37

Slide 37 text

static Flux addLogging(Flux flux) { return flux .doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... getFlux() .transform(flux -> addLogging(flux)) .subscribe(); … and use the returned value! @bsideup

Slide 38

Slide 38 text

static Flux addLogging(Flux flux) { return flux .doOnNext(it -> println("Received " + it)) .doOnError(e -> e.printStackTrace()); } // ... getFlux() .transform(flux -> addLogging(flux)) .subscribe(); … and use the returned value! @bsideup

Slide 39

Slide 39 text

Higher-order functions

Slide 40

Slide 40 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> System.out.println("User: " + user)); Higher-order functions @bsideup

Slide 41

Slide 41 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> System.out.println("User: " + user)); Higher-order functions @bsideup

Slide 42

Slide 42 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> System.out.println("User: " + user)); Higher-order functions @bsideup

Slide 43

Slide 43 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> System.out.println("User: " + user)); Higher-order functions @bsideup

Slide 44

Slide 44 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> println("User: " + user)); Higher-order functions @bsideup

Slide 45

Slide 45 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> println("User: " + user)); Higher-order functions Less scopes @bsideup

Slide 46

Slide 46 text

Mono userIdMono = getUserId(); userIdMono.subscribe(userId -> { Mono userMono = getUser(userId); userMono.subscribe(user -> { if (isUserValid(user)) { println("User: " + user); } }); }); // vs getUserId() .flatMap(userId -> getUser(userId)) .filter(user -> isUserValid(user)) .subscribe(user -> println("User: " + user)); Higher-order functions Composition @bsideup

Slide 47

Slide 47 text

Side effects are not welcomed

Slide 48

Slide 48 text

https:/ /xkcd.com/1312/ @bsideup

Slide 49

Slide 49 text

Avoid side effects Flux users = getUsers(); return users.doOnNext(user -> { storeUser(user); }); @bsideup

Slide 50

Slide 50 text

Avoid side effects Flux users = getUsers(); return users.doOnNext(user -> { storeUser(user); }); Side effect! void storeUser(User user) { // } @bsideup

Slide 51

Slide 51 text

Avoid side effects Flux users = getUsers(); return users.concatMap(user -> storeUser(user)); Mono storeUser(User user) { // } @bsideup

Slide 52

Slide 52 text

“things you do in your (async) callbacks should never take (significant) time” Stephane Maldini, 2019 @bsideup

Slide 53

Slide 53 text

Errors are side effects too return fetchUsers().map(json -> { try { return decodeJSON(json); } catch (IOException e) { throw new RuntimeException(e); } }); @bsideup

Slide 54

Slide 54 text

Errors are side effects too return fetchUsers().map(json -> { try { return decodeJSON(json); } catch (IOException e) { throw new RuntimeException(e); } }); @bsideup

Slide 55

Slide 55 text

Errors are side effects too return fetchUsers().map(json -> { try { return decodeJSON(json); } catch (IOException e) { throw new RuntimeException(e); } }); return fetchUsers().handle((json, sink) -> { try { sink.next(decodeJSON(json)); } catch (IOException e) { sink.error(e); } }); @bsideup

Slide 56

Slide 56 text

Errors are side effects too return fetchUsers().map(json -> { try { return decodeJSON(json); } catch (IOException e) { throw new RuntimeException(e); } }); return fetchUsers().handle((json, sink) -> { try { sink.next(decodeJSON(json)); } catch (IOException e) { sink.error(e); } }); @bsideup

Slide 57

Slide 57 text

Errors are side effects too return fetchUsers().map(json -> { try { return decodeJSON(json); } catch (IOException e) { throw new RuntimeException(e); } }); return fetchUsers().handle((json, sink) -> { try { sink.next(decodeJSON(json)); } catch (IOException e) { sink.error(e); } }); No need to wrap with RuntimeException @bsideup

Slide 58

Slide 58 text

use it for heavy computations DON’T @bsideup

Slide 59

Slide 59 text

~5x Overhead

Slide 60

Slide 60 text

.flatMap .concatMap(this::calculateHash) .delayUntil(this::squareRoot)

Slide 61

Slide 61 text

.flatMap .concatMap .delayUntil(this::squareRoot)

Slide 62

Slide 62 text

.flatMap .concatMap .publishOn

Slide 63

Slide 63 text

.flatMap .concatMap .publishOn Queue Queue Queue

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

check various operators DO @bsideup

Slide 67

Slide 67 text

“Reactive starter pack” • map • filter • flatMap • take • subscribeOn/publishOn @bsideup

Slide 68

Slide 68 text

@bsideup

Slide 69

Slide 69 text

@bsideup

Slide 70

Slide 70 text

“flatMaps” • flatMap - transform every item concurrently into a sub-stream, and join the current and the sub-stream. @bsideup

Slide 71

Slide 71 text

“flatMaps” • flatMap - transform every item concurrently into a sub-stream, and join the current and the sub-stream. • concatMap - same as flatMap, but one-by-one @bsideup

Slide 72

Slide 72 text

“flatMaps” • flatMap - transform every item concurrently into a sub-stream, and join the current and the sub-stream. • concatMap - same as flatMap, but one-by-one • switchMap - same as concatMap, but will cancel the previous sub- stream when a new item arrives @bsideup

Slide 73

Slide 73 text

“flatMaps” • flatMap - transform every item concurrently into a sub-stream, and join the current and the sub-stream. • concatMap - same as flatMap, but one-by-one • switchMap - same as concatMap, but will cancel the previous sub- stream when a new item arrives • flatMapSequential - same as flatMap, but preserves the order of sub- stream items according to the original stream’s order @bsideup

Slide 74

Slide 74 text

Which operator to use?

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

block non-blocking threads DON’T @bsideup

Slide 77

Slide 77 text

block non-blocking threads DON’T @bsideup

Slide 78

Slide 78 text

How reactive frameworks schedule tasks @bsideup

Slide 79

Slide 79 text

Default thread pools Schedulers.parallel() - N threads, where N matches the CPUs count. Schedulers.single() - 1 thread handling all submitted tasks Schedulers.boundedElastic() - dynamic, thread caching capped pool @bsideup

Slide 80

Slide 80 text

Mono.delay(ofSeconds(1)) @bsideup

Slide 81

Slide 81 text

Mono.delay(ofSeconds(1)) Mono.delay(ofSeconds(1), Schedulers.parallel()) @bsideup

Slide 82

Slide 82 text

Mono.delay(ofSeconds(1)) Mono.delay(ofSeconds(1), Schedulers.parallel()) Every non-instant operation 
 runs on the parallel scheduler
 by default! @bsideup

Slide 83

Slide 83 text

parallel-1 parallel-2 parallel-3 parallel-4 Non-blocking execution @bsideup

Slide 84

Slide 84 text

parallel-1 parallel-2 parallel-3 parallel-4 Non-blocking execution @bsideup

Slide 85

Slide 85 text

parallel-1 parallel-2 parallel-3 parallel-4 Non-blocking execution @bsideup

Slide 86

Slide 86 text

parallel-1 parallel-2 parallel-3 parallel-4 Non-blocking execution @bsideup

Slide 87

Slide 87 text

parallel-1 parallel-2 parallel-3 parallel-4 Non-blocking execution @bsideup

Slide 88

Slide 88 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 89

Slide 89 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 90

Slide 90 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 91

Slide 91 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 92

Slide 92 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 93

Slide 93 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 94

Slide 94 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 95

Slide 95 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 96

Slide 96 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution @bsideup

Slide 97

Slide 97 text

parallel-1 parallel-2 parallel-3 parallel-4 Blocking execution ⚠ no more tasks scheduled 
 until this task returns @bsideup

Slide 98

Slide 98 text

How to fix?

Slide 99

Slide 99 text

Project Loom

Slide 100

Slide 100 text

@bsideup

Slide 101

Slide 101 text

@bsideup

Slide 102

Slide 102 text

Use non-blocking APIs, or…

Slide 103

Slide 103 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 104

Slide 104 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 105

Slide 105 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 106

Slide 106 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 107

Slide 107 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 108

Slide 108 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 109

Slide 109 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 110

Slide 110 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 111

Slide 111 text

parallel-1 parallel-2 parallel-3 parallel-4 Custom thread pool! custom-1 custom-2 @bsideup

Slide 112

Slide 112 text

Demo http://eskipaper.com/homer-jay-simpson-cartoon.html

Slide 113

Slide 113 text

Demo outcomes • Blocking calls are bad, m’kay? • They may sneak into your production system • Use https://github.com/reactor/BlockHound to detect them • Supports multiple frameworks (Reactor, RxJava, etc) • … and maybe even Kotlin: 
 https://github.com/Kotlin/kotlinx.coroutines/issues/1031 • Use a dedicated pool for the necessary blocking calls, or schedule them on the Schedulers.boundedElastic() built-in pool if they happen rarely @bsideup

Slide 114

Slide 114 text

“I use async APIs and I am safe!”

Slide 115

Slide 115 text

Yeah… sure.

Slide 116

Slide 116 text

Or…

Slide 117

Slide 117 text

Are you sure?

Slide 118

Slide 118 text

KafkaProducer#send(ProducerRecord,Callback) @bsideup

Slide 119

Slide 119 text

KafkaProducer#send(ProducerRecord,Callback) “Asynchronously send a record to a topic and invoke the provided callback when the send has been acknowledged.” - Javadoc @bsideup

Slide 120

Slide 120 text

KafkaProducer#send(ProducerRecord,Callback) “Asynchronously send a record to a topic and invoke the provided callback when the send has been acknowledged.” - Javadoc java.lang.Error: Blocking call! java.lang.Object#wait at reactor.BlockHound$Builder.lambda$new$0(BlockHound.java:154) at reactor.BlockHound$Builder.lambda$install$8(BlockHound.java:254) at reactor.BlockHoundRuntime.checkBlocking(BlockHoundRuntime.java:43) at java.lang.Object.wait(Object.java) at org.apache.kafka.clients.Metadata.awaitUpdate(Metadata.java:181) at org.apache.kafka.clients.producer.KafkaProducer.waitOnMetadata(KafkaProducer.java:938) at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823) at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:803) @bsideup

Slide 121

Slide 121 text

KafkaProducer#send(ProducerRecord,Callback) “Asynchronously send a record to a topic and invoke the provided callback when the send has been acknowledged.” - Javadoc java.lang.Error: Blocking call! java.lang.Object#wait at reactor.BlockHound$Builder.lambda$new$0(BlockHound.java:154) at reactor.BlockHound$Builder.lambda$install$8(BlockHound.java:254) at reactor.BlockHoundRuntime.checkBlocking(BlockHoundRuntime.java:43) at java.lang.Object.wait(Object.java) at org.apache.kafka.clients.Metadata.awaitUpdate(Metadata.java:181) at org.apache.kafka.clients.producer.KafkaProducer.waitOnMetadata(KafkaProducer.java:938) at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823) at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:803) https://issues.apache.org/jira/browse/KAFKA-3539 @bsideup

Slide 122

Slide 122 text

long remainingWaitMs = maxWaitMs; long elapsed; // Issue metadata requests until we have metadata for the topic or maxWaitTimeMs is exceeded. // In case we already have cached metadata for the topic, but the requested partition is greater // than expected, issue an update request only once. This is necessary in case the metadata // is stale and the number of partitions for this topic has increased in the meantime. do { log.trace("Requesting metadata update for topic {}.", topic); metadata.add(topic); int version = metadata.requestUpdate(); sender.wakeup(); try { metadata.awaitUpdate(version, remainingWaitMs); } catch (TimeoutException ex) { // Rethrow with original maxWaitMs to prevent logging exception with remainingWaitMs throw new TimeoutException("Failed to update metadata after " + maxWaitMs + " ms."); } cluster = metadata.fetch(); elapsed = time.milliseconds() - begin; if (elapsed >= maxWaitMs) throw new TimeoutException("Failed to update metadata after " + maxWaitMs + " ms."); if (cluster.unauthorizedTopics().contains(topic)) throw new TopicAuthorizationException(topic); remainingWaitMs = maxWaitMs - elapsed; partitionsCount = cluster.partitionCountForTopic(topic); } while (partitionsCount == null); waitOnMetadata(record.topic(), record.partition(), maxBlockTimeMs); Default is “60 seconds” @bsideup

Slide 123

Slide 123 text

@bsideup

Slide 124

Slide 124 text

Start gradually DO @bsideup

Slide 125

Slide 125 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll(); } } interface UsersRepository { List findAll(); } @bsideup

Slide 126

Slide 126 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll(); } } interface UsersRepository { List findAll(); } @bsideup

Slide 127

Slide 127 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll(); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 128

Slide 128 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll(); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 129

Slide 129 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll() .collectList() .block(); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 130

Slide 130 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll() .collectList() .timeout(Mono.delay(ofSeconds(10))) .retry(5) .block(); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 131

Slide 131 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; Flux getUsers() { return usersRepository.findAll() .timeout(Mono.delay(ofSeconds(10))) .retry(5); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 132

Slide 132 text

class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers().stream() .map(UserDTO::new) .collect(Collectors.toList()); } } class UsersService { UsersRepository usersRepository; Flux getUsers() { return usersRepository.findAll() .timeout(Mono.delay(ofSeconds(10))) .retry(5); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 133

Slide 133 text

class UsersController { UsersService usersService; @GetMapping("/users") Flux getUsers() { return usersService.getUsers() .map(UserDTO::new); } } class UsersService { UsersRepository usersRepository; Flux getUsers() { return usersRepository.findAll() .timeout(Mono.delay(ofSeconds(10))) .retry(5); } } interface UsersRepository { Flux findAll(); } @bsideup

Slide 134

Slide 134 text

Before: class UsersController { UsersService usersService; @GetMapping("/users") List getUsers() { return usersService.getUsers() .stream() .map(UserDTO::new) .collect(toList()); } } class UsersService { UsersRepository usersRepository; List getUsers() { return usersRepository.findAll(); } } interface UsersRepository { List findAll(); } class UsersController { UsersService usersService; @GetMapping("/users") Flux getUsers() { return usersService.getUsers() .map(UserDTO::new); } } class UsersService { UsersRepository usersRepository; Flux getUsers() { return usersRepository.findAll() .timeout(Mono.delay(ofSeconds(10))) .retry(5); } } interface UsersRepository { Flux findAll(); } After:

Slide 135

Slide 135 text

use ThreadLocals DON’T @bsideup

Slide 136

Slide 136 text

Synchronous programming • 1 request == 1 thread • Everything is blocking, the execution continues on the same thread • ThreadLocals work just fine @bsideup

Slide 137

Slide 137 text

Asynchronous programming • 1 request will most probably be handled by multiple threads • Everything is non-blocking, an accepted request may be returned to the client from another thread • ThreadLocals must be propagated from one thread to another @bsideup

Slide 138

Slide 138 text

Solution?

Slide 139

Slide 139 text

Context!

Slide 140

Slide 140 text

Mono .deferWithContext(ctx -> { return this.getUser(ctx.get("userId")); }) // Later in the framework (e.g. Spring Security) .subscriberContext(Context.of("userId", "bsideup")) .subscribe(); @bsideup

Slide 141

Slide 141 text

Mono .deferWithContext(ctx -> { return this.getUser(ctx.get("userId")); }) // Later in the framework (e.g. Spring Security) .subscriberContext(Context.of("userId", "bsideup")) .subscribe(); @bsideup

Slide 142

Slide 142 text

Mono .deferWithContext(ctx -> { return this.getUser(ctx.get("userId")); }) // Later in the framework (e.g. Spring Security) .subscriberContext(Context.of("userId", "bsideup")) .subscribe(); @bsideup

Slide 143

Slide 143 text

Legacy?

Slide 144

Slide 144 text

Schedulers.onScheduleHook(fn) @bsideup

Slide 145

Slide 145 text

Schedulers.onScheduleHook(fn) @bsideup Schedulers.onScheduleHook("myHook", runnable -> { println("Before every scheduled runnable"); return () -> { println("Before execution"); runnable.run(); println("After execution"); }; });

Slide 146

Slide 146 text

Schedulers.onScheduleHook(fn) @bsideup Schedulers.onScheduleHook("mdc", runnable -> { String userId = MDC.get("userId"); return () -> { MDC.put("userId", userId); try { runnable.run(); } finally { MDC.remove("userId"); } }; });

Slide 147

Slide 147 text

think about the resiliency DO @bsideup

Slide 148

Slide 148 text

“Error… is a signal.” Stephane Maldini, year unknown @bsideup

Slide 149

Slide 149 text

Resiliency with Reactor @bsideup

Slide 150

Slide 150 text

Resiliency with Reactor • .timeout(Duration) - cancel the subscription and fail if no items emitted @bsideup

Slide 151

Slide 151 text

Resiliency with Reactor • .timeout(Duration) - cancel the subscription and fail if no items emitted • .retry()/retryWithBackoff() - retry the subscription on failure @bsideup

Slide 152

Slide 152 text

Resiliency with Reactor • .timeout(Duration) - cancel the subscription and fail if no items emitted • .retry()/retryWithBackoff() - retry the subscription on failure • .repeatWhenEmpty() - repeat the subscription when it completes without values @bsideup

Slide 153

Slide 153 text

Resiliency with Reactor • .timeout(Duration) - cancel the subscription and fail if no items emitted • .retry()/retryWithBackoff() - retry the subscription on failure • .repeatWhenEmpty() - repeat the subscription when it completes without values • .defaultIfEmpty() - fallback when empty @bsideup

Slide 154

Slide 154 text

Resiliency with Reactor • .timeout(Duration) - cancel the subscription and fail if no items emitted • .retry()/retryWithBackoff() - retry the subscription on failure • .repeatWhenEmpty() - repeat the subscription when it completes without values • .defaultIfEmpty() - fallback when empty • .onErrorResume() - fallback on error @bsideup

Slide 155

Slide 155 text

Distributed?

Slide 156

Slide 156 text

https://github.com/resilience4j/resilience4j RateLimiter rateLimiter = RateLimiter.ofDefaults(“name"); Mono.fromCallable(backendService::doSomething) .transformDeferred(RateLimiterOperator.of(rateLimiter))

Slide 157

Slide 157 text

care about the threads DON’T @bsideup

Slide 158

Slide 158 text

You may ask… • “How do I get the current Scheduler?” • “Why does flatMap changes the thread?” • …”Why it does not?” @bsideup

Slide 159

Slide 159 text

The answer is…

Slide 160

Slide 160 text

You.

Slide 161

Slide 161 text

You. Should.

Slide 162

Slide 162 text

You. Should. Not.

Slide 163

Slide 163 text

You. Should. Not. Care.

Slide 164

Slide 164 text

Prepare for day 2 DO @bsideup

Slide 165

Slide 165 text

Demo http://eskipaper.com/homer-jay-simpson-cartoon.html

Slide 166

Slide 166 text

Demo outcomes • Use .checkpoint(“something”) to “mark” reactive “milestones” • Read about Hooks.onOperatorDebug()… • … but use reactor-tools’ ReactorDebugAgent (works in prod too) • https://spring.io/blog/2019/03/06/flight-of-the-flux-1-assembly-vs- subscription - great article from Simon Basle about the internals @bsideup

Slide 167

Slide 167 text

Be afraid of reactive programming ;) DON’T @bsideup

Slide 168

Slide 168 text

@bsideup

Slide 169

Slide 169 text

Spring Webflux @bsideup

Slide 170

Slide 170 text

Developer experience is one of the main focuses in Reactor 3.3…

Slide 171

Slide 171 text

… and we just started

Slide 172

Slide 172 text

Summary • Learn functional programming • Check various operators • Think about the resiliency • Start gradually • Prepare for day 2 • Use it for heavy computations • Care about the threads • Block non-blocking threads • Use ThreadLocals • Be afraid of it ;) DO… DON’T… @bsideup

Slide 173

Slide 173 text

@bsideup bsideup