Debian Codegraph @

vignettes/promises_08_casestudy.Rmd

raw
1 ---
2 title: "Case study: converting a Shiny app to async"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Case study: converting a Shiny app to async}
6 %\VignetteEncoding{UTF-8}
7 %\VignetteEngine{knitr::rmarkdown}
8 ---
9
10 In this case study, we'll work through an application of reasonable complexity, turning its slowest operations into mirai/promises and modifying all the downstream reactive expressions and outputs to deal with promises.
11
12 ## Motivation
13
14 > As a web service increases in popularity, so does the number of rogue scripts that abuse it for no apparent reason.
15 >
16 > _—Joe Cheng's Law of Why We Can't Have Nice Things_
17
18 I first noticed this in 2011, when the then-new RStudio IDE was starting to gather steam. We had a dashboard that tracked how often RStudio was being downloaded, and the numbers were generally tracking smoothly upward. But once every few months, we'd have huge spikes in the download counts, ten times greater than normal—and invariably, we'd find that all of the unexpected increase could be tracked to one or two IP addresses.
19
20 For hours or days we'd be inundated with thousands of downloads per hour, then just as suddenly, they'd cease. I didn't know what was happening then, and I still don't know today. Was it the world's least competent denial-of-service attempt? Did someone write a download script with an accidental `while (TRUE)` around it?
21
22 Our application will let us examine downloads from CRAN for this kind of behavior. For any given day on CRAN, we'll see what the top downloaders are and how they're behaving.
23
24 ## Our source data
25
26 RStudio maintains the popular `0-Cloud` CRAN mirror, and the log files it generates are freely available at http://cran-logs.rstudio.com/. Each day is a separate gzipped CSV file, and each row is a single package download. For privacy, IP addresses are anonymized by substituting each day's IP addresses with unique integer IDs.
27
28 Here are the first few lines of http://cran-logs.rstudio.com/2018/2018-05-26.csv.gz :
29
30 ```
31 "date","time","size","r_version","r_arch","r_os","package","version","country","ip_id"
32 "2018-05-26","20:42:23",450377,"3.4.4","x86_64","linux-gnu","lubridate","1.7.4","NL",1
33 "2018-05-26","20:42:30",484348,NA,NA,NA,"homals","0.9-7","GB",2
34 "2018-05-26","20:42:21",98484,"3.3.1","x86_64","darwin13.4.0","miniUI","0.1.1.1","NL",1
35 "2018-05-26","20:42:27",518,"3.4.4","x86_64","linux-gnu","RCurl","1.95-4.10","US",3
36 ```
37
38 Fortunately for our purposes, there's no need to analyze these logs at a high level to figure out which days are affected by badly behaved download scripts. These CRAN mirrors are popular enough that, according to Cheng's Law, there should be plenty of rogue scripts hitting it every day of the year.
39
40 ## A tour of the app
41
42 The app I built to explore this data, **cranwhales**, let us examine the behavior of the top downloaders ("whales") for any given day, at varying levels of detail. You can view this app live at https://gallery.shinyapps.io/cranwhales/, or download and run the code yourself at https://github.com/rstudio/cranwhales.
43
44 When the app starts, the "All traffic" tab shows you the number of package downloads per hour for all users vs. whales. In this screenshot, you can see the proportion of files downloaded by the top six downloaders on May 28, 2018. It may not look like a huge fraction at first, but keep in mind, we are only talking about six downloaders out of 52,815 total!
45
46 !["All traffic" app tab displaying histogram of top six downloaders.](case-study-tab1.png)
47
48 The "Biggest whales" tab simply shows the most prolific downloaders, with their number of downloads performed. Each anonymized IP address has been assigned an easier-to-remember name, and you can also see the country code of the original IP address.
49
50 !["Biggest whales" app tab displays excessive download counts for top 6 downloaders.](case-study-tab2.png)
51
52 The "Whales by hour" tab shows the hourly download counts for each whale individually. In this screenshot, you can see that the Netherlands' `relieved_snake` downloaded at an extremely consistent rate during the whole day, while the American `curly_capabara` was active only during business hours in Eastern Standard Time. Still others, like `colossal_chicken` out of Hong Kong, was busy all day but at varying rates.
53
54 !["Whales by hour" app tab shows hourly pattern of each _whale_.](case-study-tab3.png)
55
56 The "Detail View" has perhaps the most illuminating information. It lets you view every download made by a given whale on the day in question. The x dimension is time and the y dimension is what package they downloaded, so you can see at a glance exactly how many packages were downloaded, and how their various package downloads relate to each other. In this case, `relieved_snake` downloaded 104 different packages, in the same order, continuously, for the entire day.
57
58 !["Detail View" showing how `relieved_snake` downloads 104 packages continuously all day long.](case-study-tab4.png)
59
60 Others behave very differently, like `freezing_tapir`, who downloaded `devtools`--and _only_ `devtools`--for the whole day, racking up 19,180 downloads totalling 7.9 gigabytes for that one package alone!
61
62 !["Detail View" showing how `freezing_tapir` only downloads `{devtools}` continuously all day long.](case-study-tab5.png)
63
64 Sadly, the app can't tell us any more than that--it can't explain _why_ these downloaders are behaving this way, nor can it tell us their street addresses so that we can send ninjas in black RStudio helicopters to make them stop.
65
66 ## The implementation
67
68 Now that you've seen what the app does, let's talk about how it was implemented, then convert it from sync to async.
69
70 ### User interface
71
72 The user interface is a pretty typical shinydashboard. It's important to note that the UI part of the app is entirely agnostic to whether the server is written in the sync or async style; when we port the app to async, we won't touch the UI at all.
73
74 There are two major pieces of input we need from users: what **date** to examine (this app only lets us look at one day at a time) and **how many** of the most prolific downloaders to look at. We'll put these two controls in the dashboard sidebar.
75
76 ```r
77 dashboardSidebar(
78 dateInput("date", "Date", value = Sys.Date() - 2),
79 numericInput("count", "Show top N downloaders:", 6)
80 )
81 ```
82
83 (We set `date` to two days ago by default, because there's some lag between when a day ends and when its logs are published.)
84
85 The rest of the UI code is just typical shinydashboard scaffolding, plus some `shinydashboard::valueBoxOutput`s and `plotOutputs`. These are so trivial that they're hardly worth talking about, but I'll include the code here for completeness. Finally, there's `detailViewUI`, a [Shiny module](https://shiny.posit.co/r/articles/improve/modules/) that just contains more of the same (value boxes and plots).
86
87 ```r
88 dashboardBody(
89 fluidRow(
90 tabBox(width = 12,
91 tabPanel("All traffic",
92 fluidRow(
93 valueBoxOutput("total_size", width = 4),
94 valueBoxOutput("total_count", width = 4),
95 valueBoxOutput("total_downloaders", width = 4)
96 ),
97 plotOutput("all_hour")
98 ),
99 tabPanel("Biggest whales",
100 plotOutput("downloaders", height = 500)
101 ),
102 tabPanel("Whales by hour",
103 plotOutput("downloaders_hour", height = 500)
104 ),
105 tabPanel("Detail view",
106 detailViewUI("details")
107 )
108 )
109 )
110 )
111 ```
112
113 ### Server logic
114
115 Based on these inputs and outputs, we'll write a variety of reactive expressions and output renderers to download, manipulate, and visualize the relevant log data.
116
117 The reactive expressions:
118
119 * `data` (`eventReactive`): Whenever `input$date` changes, the `data` reactive downloads the full log for that day from http://cran-logs.rstudio.com, and parses it.
120 * `whales` (`reactive`): Reads from `data()`, tallies the number of downloads performed by each unique IP, and returns a data frame of the top `input$count` most prolific downloaders, along with their download counts.
121 * `whale_downloads` (`reactive`): Joins the `data()` and `whales()` data frames, to return all of the details of the cetacean downloads.
122
123 The `whales` reactive expression depends on `data`, and `whale_downloads` depends on `data` and `whales`.
124
125 ![Reactive dependencies of an application.](case-study-react.png)
126
127 The outputs in this app are mostly either `renderPlot`s that we populate with `ggplot2`, or `shinydashboard::renderValueBox`es. They all rely on one or more of the reactive expressions we just described. We won't catalog them all here, as they're not individually interesting, but we will look at some archetypes below.
128
129 ## Improving performance and scalability
130
131 While this article is specifically about async, this is a good time to remind you that there are lots of ways to improve the performance of a Shiny app. Async is just one tool in the toolbox, and before reaching for that hammer, take a moment to consider your other options:
132
133 1. Have I used [profvis](https://profvis.r-lib.org/) to **profile my code** and determine what's actually taking so long? (Human intuition is a notoriously bad profiler!)
134 2. Can I perform any **calculations, summarizations, and aggregations offline**, when my Shiny app isn't even running, and save the results to .rds files to be read by the app?
135 3. Are there any opportunities to **cache**--that is, save the results of my calculations and use them if I get the same request later? (See [memoise](https://cran.r-project.org/package=memoise), or roll your own.)
136 4. Am I effectively leveraging [reactive programming](https://posit.co/resources/videos/reactivity-pt-1-joe-cheng/) to make sure my reactives are doing as little work as possible?
137 5. When deploying my app, am I load balancing across multiple R processes and/or multiple servers? ([Shiny Server Pro](https://docs.posit.co/shiny-server/), [RStudio Connect](https://docs.posit.co/connect/admin/appendix/configuration/), [ShinyApps.io](https://shiny.posit.co/r/articles/improve/scaling-and-tuning/))
138
139 These options are more generally useful than using async techniques because they can dramatically speed up the performance of an app even if only a single user is using it. While it obviously depends on the particulars of the app itself, a few lines of precomputation or caching logic can often lead to 10X-100X better performance. Async, on the other hand, generally doesn't help make a single session faster. Instead, it helps a single Shiny process support more concurrent sessions without getting bogged down.
140
141 Async can be an essential tool when there is no way around performing expensive tasks (i.e. taking multiple seconds) while the user waits. For example, an app that analyzes any user-specified Twitter profile may get too many unique queries (assuming most people specify their own Twitter handle) for caching to be much help. And applications that invite users to upload their own datasets won't have an opportunity to do any offline summarizing in advance. If you need to run apps like that and support lots of concurrent users, async can be a huge help.
142
143 In that sense, the cranwhales app isn't a perfect example, because it has lots of opportunities for precomputation and caching that we'll willfully ignore today so that I can better illustrate the points I want to make about async. When you're working on your own app, though, please think carefully about _all_ of the different techniques you have for improving performance.
144
145 ## Converting to async
146
147 To quote the article [*Using promises with Shiny*](https://rstudio.github.io/promises/articles/promises_06_shiny.html), async programming with Shiny boils down to following a few steps:
148
149 1. Identify slow operations in your app.
150 2. Convert the slow operations into mirai.
151 3. Any code that relies on the result of those operations (if any), whether directly or indirectly, now must be converted to promise handlers that operate on the mirai object.
152
153 In this case, the slow operations are easy to identify: the downloading and parsing that takes place in the `data` reactive expression can each take several long seconds.
154
155 Converting the download and parsing operations into mirai turns out to be the most complicated part of the process, for reasons we'll get into later.
156
157 Assuming we do that successfully, the `data` reactive expression will no longer return a data frame, but a `promise` object (that resolves to a data frame). Since the `whales` and `whale_downloads` reactive expressions both rely on `data`, those will both also need to be converted to read and return `promise` objects. And therefore, because the outputs all rely on one or more reactive expressions, they will all need to know how to deal with `promise` objects.
158
159 Async code is infectious like that; once you turn the heart of your app into a promise, everything downstream must become promise-aware as well, all the way through to the observers and outputs.
160
161 With that overview out of the way, let's dive into the code.
162
163 In the sections below, we'll take a look at the code behind some outputs and reactive expressions. For each element, we'll look first at the sync version, then the async version.
164
165 In some cases, these code snippets may be slightly abridged. See the [GitHub repository](https://github.com/rstudio/cranwhales) for the full code.
166
167 Until you've received an introduction to `lhs |> then(func)` chaining, the async code below will make no sense, so if you haven't read [*An informal intro to async programming*](https://rstudio.github.io/promises/articles/promises_02_intro.html) and/or [*Working with promises in R*](https://rstudio.github.io/promises/articles/promises_03_overview.html), I highly recommend doing so before continuing!
168
169 ### Loading `promises` and `mirai`
170
171 The first thing we'll do is load the basic libraries of async programming.
172
173 ```r
174 library(promises)
175 library(mirai)
176 daemons(6)
177 ```
178
179 The above sets 6 daemons (background processes) on the local machine, but this could also be anything else supported by the `daemons()` function.
180
181 ### The `data` reactive: mirai() all the things
182
183 The next thing we'll do is convert the `data` event reactive to use `mirai` for the expensive bits. The original code looks lke this:
184
185 ```r
186 # SYNCHRONOUS version
187
188 data <- eventReactive(input$date, {
189 date <- input$date # Example: 2018-05-28
190 year <- lubridate::year(date) # Example: "2018"
191
192 url <- glue("http://cran-logs.rstudio.com/{year}/{date}.csv.gz")
193 path <- file.path("data_cache", paste0(date, ".csv.gz"))
194
195 withProgress(value = NULL, {
196
197 if (!file.exists(path)) {
198 setProgress(message = "Downloading data...")
199 download.file(url, path)
200 }
201
202 setProgress(message = "Parsing data...")
203 read_csv(path, col_types = "Dti---c-ci", progress = FALSE)
204
205 })
206 })
207 ```
208
209 (Earlier, I said we wouldn't take advantage of precomputation or caching. That wasn't entirely true; in the code above, we cache the log files we download in a `data_cache` directory. I couldn't bring myself to put my internet connection through that level of abuse, as I knew I'd be running this code thousands of times as I load tested it.)
210
211 For now, we'll lose the `withProgress`/`setProgress` reporting, since doing that correctly requires some more advanced techniques that we'll talk about later. We'll come back and fix this code later, but for now:
212
213 ```r
214 # ASYNCHRONOUS version
215
216 data <- eventReactive(input$date, {
217 date <- input$date
218 year <- lubridate::year(date)
219
220 url <- glue("http://cran-logs.rstudio.com/{year}/{date}.csv.gz")
221 path <- file.path("data_cache", paste0(date, ".csv.gz"))
222
223 mirai(
224 {
225 if (!file.exists(path)) {
226 download.file(url, path)
227 }
228 read_csv(path, col_types = "Dti---c-ci", progress = FALSE)
229 },
230 path = path,
231 url = url
232 )
233 })
234 ```
235
236 Pretty straightforward. This reactive now returns a mirai (which counts as a promise), not a data frame.
237
238 Remember that we **must** read any reactive values (including `input`) and reactive expressions [from **outside** the mirai](https://rstudio.github.io/promises/articles/promises_06_shiny.html#shiny-specific-caveats-and-limitations). (You will get an error if you attempt to read one from inside the mirai.)
239
240 At this point, since there are no other long-running operations we want to make asynchronous, we're actually done interacting directly with the `mirai` package. The rest of the reactive expressions will deal with the mirai returned by `data` using general async functions and operators from `promises`.
241
242 ### The `whales` reactive: simple pipelines are simple
243
244 The `whales` reactive takes the data frame from `data`, and uses dplyr to find the top `input$count` most prolific downloaders.
245
246 ```r
247 # SYNCHRONOUS version
248
249 whales <- reactive({
250 data() |>
251 count(ip_id) |>
252 arrange(desc(n)) |>
253 head(input$count)
254 })
255 ```
256
257 Since `data()` now returns a promise, the whole function needs to be modified to deal with promises.
258
259 This is basically a best-case scenario for working with `promises`. The whole expression consists of native pipes. There's only one object (`data()`) that's been converted to a promise. The promise object only appears once, at the head of the pipeline.
260
261 When the stars align like this, converting this code to async is literally as easy as wrapping each line in an anonymous function inside `then()`:
262
263 ```r
264 # ASYNCHRONOUS version
265
266 whales <- reactive({
267 data() |>
268 then(\(df) df |> count(ip_id)) |>
269 then(\(df) df |> arrange(desc(n))) |>
270 then(\(df) df |> head(input$count))
271 })
272 ```
273
274 The input (`data()`) is a promise, the resulting output object is a promise, each stage of the pipeline returns a promise; but we can read and write this code almost as easily as the synchronous version!
275
276 An example this simple may seem reductive, but this best-case scenario happens surprisingly often, if your coding style is influenced by the tidyverse. In this example app, **59%** of the reactives, observers, and outputs were converted using nothing more than replacing `|>` with `then()`.
277
278 One last thing before we move on. In the last section, I emphasized that reactive values cannot be read from inside a mirai. Here, we're using `head(input$count)` inside a promise-pipeline; since `data()` is written using a mirai, doesn't that mean… well… isn't this wrong?
279
280 Nope—this code is just fine. The prohibition is against reading reactive values/expressions from *inside* a mirai, because code inside a mirai is executed in a totally different R process. The steps in a promise-pipeline are not mirai, but promise handlers. These aren't executed in a different process; rather, they're executed back in the original R process after a promise is resolved. We're allowed and expected to access reactive values and expressions from these handlers.
281
282 ### The `whale_downloads` reactive: reading from multiple promises
283
284 The `whale_downloads` reactive is a bit more complicated case.
285
286 ```r
287 # SYNCHRONOUS version
288
289 whale_downloads <- reactive({
290 data() |>
291 inner_join(whales(), "ip_id") |>
292 select(-n)
293 })
294 ```
295
296 Looks simple, but we can't just do a simple replacement this time. Can you see why?
297
298 ```r
299 # BAD VERSION DOESN'T WORK
300
301 whale_downloads <- reactive({
302 data() |>
303 then(\(df) df |> inner_join(whales(), "ip_id")) |>
304 then(\(df) df |> select(-n))
305 })
306 ```
307
308 Remember, both `data()` and `whales()` now return a promise object, not a data frame. None of the dplyr verbs know how to deal with promises natively (and the same is true for almost every other R function, anywhere in the R universe).
309
310 We're able to use `then()` with promises on the left-hand side and regular dplyr calls on the right-hand side, only because the `then()` operator "unwraps" the promise object for us, yielding a regular object (data frame or whatever) to be passed to dplyr. But in this case, we're passing `whales()`, which a promise object, directly to `inner_join`, and `inner_join` has no idea what to do with it.
311
312 The fundamental thing to pattern-match on here, is that **we have a block of code that relies on more than one promise object**, and that means `then()` won't be enough. This is a pretty common situation as well, and occurs in **12%** of reactives and outputs in this example app.
313
314 Here's what the real solution looks like:
315
316 ```r
317 # ASYNCHRONOUS version
318
319 whale_downloads <- reactive({
320 promise_all(data_df = data(), whales_df = whales()) |>
321 then(\(values) {
322 with(values, {
323 data_df |>
324 inner_join(whales_df, "ip_id") |>
325 select(-n)
326 })
327 })
328 ```
329
330 #### Promises: the Gathering
331
332 This solution uses the [promise gathering](https://rstudio.github.io/promises/articles/promises_07_combining.html#gathering) pattern, which combines `promises_all`, `then`, and `with`.
333
334 * The `promise_all` function gathers multiple promise objects together, and returns a single promise object. This new promise object doesn't resolve until all the input promise objects are resolved, and it yields a list of those results.
335
336 ```r
337 promise_all(a = mirai("Hello"), b = mirai("World")) |> then(print)
338 #> $a
339 #> [1] "Hello"
340 #>
341 #> $b
342 #> [1] "World"
343 ```
344
345 * The `then`, as before, "unwraps" the promise object and passes the result to its right hand side.
346 * The `with` function (from base R) takes a named list, and makes it into a sort of virtual parent environment while evaluating a code block you pass it.
347
348 ```r
349 x + y
350 #> Error: object 'x' not found
351
352 with(list(x = 1, y = 2), {
353 x + y
354 })
355 #> [1] 3
356 ```
357
358 Let's once again combine the three, with the simplest possible example of the gathering pattern:
359
360 ```r
361 promise_all(x = mirai("Hello"), y = mirai("World")) |>
362 then(\(values) with(values, {
363 paste(x, y)
364 })) |>
365 then(print)
366 #> [1] "Hello World"
367 ```
368
369 You can make use of this pattern without remembering exactly how these pieces combine. Just remember that the arguments to `promise_all` provide the promise objects (`mirai(1)` and `mirai(2)`), along with the names you want to use to refer to their yielded values (`x ` and `y`); and the code block you put in `with()` can refer to those names without worrying about the fact that they were ever promises to begin with.
370
371 ### The `total_downloaders` value box: simple pipelines are for output, too
372
373 ![Over 52 thousand unique downloaders](case-study-downloaders.png)
374
375 All of the value boxes in this app ended up looking a lot like this:
376
377 ```r
378 # SYNCHRONOUS version
379
380 output$total_downloaders <- renderValueBox({
381 data() |>
382 pull(ip_id) |>
383 unique() |>
384 length() |>
385 format(big.mark = ",") |>
386 valueBox("unique downloaders")
387 })
388 ```
389
390 This is structurally no different than the `whales` best-case scenario reactive. One thing worth pointing out is that an async `renderValueBox` means you return a promise that returns a `valueBox`; you *don't* return a `valueBox` to whom you have passed a promise.
391
392 Meaning, you *don't* do this:
393
394 ```r
395 # BAD VERSION DOESN'T WORK
396
397 output$total_downloaders <- renderValueBox({
398 valueBox(
399 data() |>
400 then(\(df) pull(df, ip_id)) |>
401 then(\(col) unique(col)) |>
402 then(length) |>
403 then(\(n) format(n, big.mark = ",")),
404 "unique downloaders"
405 )
406 })
407 ```
408
409 Instead, you do this:
410
411 ```r
412 # ASYNCHRONOUS version
413
414 output$total_downloaders <- renderValueBox({
415 data() |>
416 then(\(df) pull(df, ip_id)) |>
417 then(\(col) unique(col)) |>
418 then(length) |>
419 then(\(n) format(n, big.mark = ",")) |>
420 then(\(val) valueBox(val, "unique downloaders"))
421 })
422 ```
423
424 The other trick worth nothing is the `pull` verb, which is used to retrieve a specific column of a data frame as a vector (similar to `$` or `[[`). In this case, `pull(data, ip_id)` is equivalent to `data[["ip_id"]]`. Note that `pull` is part of dplyr and isn't specific to promises.
425
426 ### The `biggest_whales` plot: getting untidy
427
428 In a cruel twist of API design fate, one of the cornerstone packages of the tidyverse lacks a tidy API. I'm referring, of course, to `ggplot2`:
429
430 ```r
431 # SYNCHRONOUS version
432
433 output$downloaders <- renderPlot({
434 whales() |>
435 ggplot(aes(ip_name, n)) +
436 geom_bar(stat = "identity") +
437 ylab("Downloads on this day")
438 })
439 ```
440
441 While `dplyr` and other tidyverse packages are designed to link calls together with `|>`, the older `ggplot2` package uses the `+` operator. This is mostly a small aesthetic wart when synchronous code, but it's a real problem with async, because the `promises` package doesn't currently have a promise-aware replacement for `+` like it does for `|>`.
442
443 Instead of a pipeline stage being a simple function call, you can perform a multi-line code block inside a `then()` wrapper.
444
445 ```r
446 # ASYNCHRONOUS version
447
448 output$downloaders <- renderPlot({
449 whales() |>
450 then(\(whale_df) {
451 ggplot(whale_df, aes(ip_name, n)) +
452 geom_bar(stat = "identity") +
453 ylab("Downloads on this day")
454 })
455 })
456 ```
457
458 **The importance of this pattern cannot be overstated!** Using `then()` and simple calls alone, you're restricted to doing pipeline-compatible operations. But `then()` together with a curly-brace code block means your handler code can be any shape or size. You can have zero, one, or more statements.
459
460
461 ### Revisiting the `data` reactive: progress support
462
463 Now that we have discussed a few techniques for writing async code, let's come back to our original `data` event reactive, and this time do a more faithful async conversion that preserves the progress reporting functionality of the original.
464
465 Again, here's the original sync code:
466
467 ```r
468 # SYNCHRONOUS version
469
470 data <- eventReactive(input$date, {
471 date <- input$date # Example: 2018-05-28
472 year <- lubridate::year(date) # Example: "2018"
473
474 url <- glue("http://cran-logs.rstudio.com/{year}/{date}.csv.gz")
475 path <- file.path("data_cache", paste0(date, ".csv.gz"))
476
477 withProgress(value = NULL, {
478
479 if (!file.exists(path)) {
480 setProgress(message = "Downloading data...")
481 download.file(url, path)
482 }
483
484 setProgress(message = "Parsing data...")
485 read_csv(path, col_types = "Dti---c-ci", progress = FALSE)
486
487 })
488 })
489 ```
490
491 Progress reporting currently presents two challenges for mirai.
492
493 First, the `withProgress({...})` function cannot be used with async. `withProgress` is designed to wrap a slow synchronous action, and dismisses its progress dialog when the block of code it wraps is done executing. Since the call to `mirai()` will return immediately even though the actual task is far from done, using `withProgress` won't work; the progress dialog would be dismissed before the download even got going.
494
495 It's conceivable that `withProgress` could gain promise compatibility someday, but it's not in Shiny v1.1.0. In the meantime, we can work around this by using the alternative, [object-oriented progress API](https://shiny.posit.co/r/reference/shiny/latest/progress.html) that Shiny offers. It's a bit more verbose and fiddly than `withProgress`/`setProgress`, but it is flexible enough to work with mirai/promises.
496
497 Second, progress messages can't be sent from mirai. This is simply because mirai are executed in child processes, which don't have direct access to the browser like the main Shiny process does.
498
499 It's conceivable that `mirai` could gain the ability for child processes to communicate back to their parents, but no good solution exists at the time of this writing. In the meantime, we can work around this by taking the one mirai that does both downloading and parsing, and splitting it into two separate mirai. After the download mirai has completed, we can send a progress message that parsing is beginning, and then start the parsing mirai.
500
501 The regrettably complicated solution is below.
502
503 ```r
504 # ASYNCHRONOUS version
505
506 data <- eventReactive(input$date, {
507 date <- input$date
508 year <- lubridate::year(date)
509
510 url <- glue("http://cran-logs.rstudio.com/{year}/{date}.csv.gz")
511 path <- file.path("data_cache", paste0(date, ".csv.gz"))
512
513 p <- Progress$new()
514 p$set(value = NULL, message = "Downloading data...")
515 mirai(
516 {
517 if (!file.exists(path)) {
518 download.file(url, path)
519 }
520 },
521 path = path,
522 url = url
523 ) |>
524 then(\() p$set(message = "Parsing data...") ) |>
525 then(\() {
526 mirai(
527 {
528 read_csv(path, col_types = "Dti---c-ci", progress = FALSE)
529 },
530 path = path
531 )
532 }) |>
533 finally(\() p$close())
534 })
535 ```
536
537 The single mirai we wrote earlier has now become a pipeline of promises:
538
539 1. mirai (download)
540 2. send progress message
541 3. mirai (parse)
542 4. dismiss progress dialog
543
544 Note that neither the R6 call `p$set(message = ...)` nor the second `mirai()` call are tidy, so they use curly-brace blocks, as discussed in the above section about `biggest_whales`.
545
546 The final step of dismissing the progress dialog doesn't use `then()` at all; because we want the progress dialog to dismiss whether the download and parse operations succeed or fail, we use `finally()` operator instead. See the relevant section in [*Working with promises in R*](https://rstudio.github.io/promises/articles/promises_03_overview.html#cleaning-up-with-finally) to learn more.
547
548 With these changes in place, we've now covered all of the changes to the application. You can see the full changes side-by-side via [this GitHub diff](https://github.com/rstudio/cranwhales/compare/sync...async?diff=split).
549
550 ## Measuring scalability
551
552 It was a fair amount of work to do the sync-to-async conversion. Now we'd like to know if the conversion to async had the desired effect: improved responsiveness (i.e. lower latency) when the number of simultaneous visitors increases.
553
554 ### Load testing with Shiny (coming soon)
555
556 At the time of this writing, we are working on a suite of load testing tools for Shiny that is not publicly available yet, but was previewed by Sean Lopp during his [epic rstudio::conf 2018 talk](https://posit.co/resources/) about running a Shiny load test with 10,000 simulated concurrent users.
557
558 You use these tools to easily **record** yourself using your Shiny app, which creates a test script; then **play back** that test script, but multiplied by dozens/hundreds/thousands of simulated concurrent users; and finally, **analyze** the timing data generated during the playback step to see what kind of latency the simulated users experienced.
559
560 To examine the effects of my async refactor, I recorded a simple test script by loading up the app, waiting for the first tab to appear, then clicking through each of the other tabs, pausing for several seconds each time before moving on to the next. When using the app without any other visitors, the homepage fully loads in less than a second, and the initial loading of data and rendering of the plot on the default tab takes about 7 seconds. After that, each tab takes no more than a couple of seconds to load. Overall, the entire test script, including time where the user is thinking, takes about 40 seconds under ideal settings (i.e. only a single concurrent user).
561
562 I then used this test script to generate load against the Shiny app running in my local RStudio. With the settings I chose, the playback tool introduced one new "user" session every 5 seconds, until 50 sessions total had been launched; then it waited until all the sessions were complete. I ran this test on both the sync and async versions in turn, which generated the following results.
563
564 ### Sync vs. async performance
565
566 ![Slower response time of sync served home pages](case-study-gantt-async.png)
567
568 In this plot, each row represents a single session, and the x dimension represents time. Each of the rectangles represents a single "step" in the test script, be it downloading the HTML for the homepage, fetching one of the two dozen JavaScript/CSS files, or waiting for the server to update outputs. So the wider a rectangle is, the longer the user had to wait. (The empty gaps between rectangles represents time the app is waiting for the user to click an input; their widths are hard-coded into the test script.)
569
570 Of particular importance are the red and pink rectangles, as these represent the initial page load. While these are taking place, the user is staring at a blank page, probably wondering if the server is down. Long waits during this stage are not only undesirable, but surprising and incomprehensible to the user; whereas the same user is probably prepared to wait a little while for a complicated visualization to be rendered in response to an input change.
571
572 And as you can see from this plot, the behavior of the async app is much improved in the critical metric of homepage/JS/CSS loading time. The sync version of the app starts displaying unacceptably long red/pink loading times as early as session 15, and by session #44 the maximum page load time has exceeded one minute. The async version at that point is showing 25 second load times, which is far from great, but still a significant step in the right direction.
573
574 ### Further optimizations
575
576 I was surprised that the async version's page load times weren't even faster, and even more surprised to see that the blue rectangles were just as wide as the sync version. Why isn't the async version way faster? The sync version does all of its work on a single thread, and I specifically designed this app to be a nightmare for scalability by having each session kick off by parsing hundreds of megabytes of CSV, an operation that is quite expensive. The async version gets to spread these jobs across several workers. Why aren't we seeing a greater time savings?
577
578 Mostly, it's because calling `mirai(read_csv("big_file.csv"))` is almost a worst-case scenario for mirai and async. `read_csv` is generally fast, but because the CRAN log files are so big, `read_csv("big_file.csv")` is slow. The value it returns is a very large data frame, that has now been loaded not into the Shiny process, but a `mirai` daemon process. In order to return that data frame to the Shiny process, that data must first be serialized, transmitted to the Shiny process, and then deserialized; to make matters worse, the transmitting and deserialization steps happen on the main R thread that we're working so hard to try to keep idle. **The larger the data we send back and forth to the mirai, the more performance suffers,** and in this case we're sending back quite a lot of data.
579
580 We can make our code significantly faster by doing more summarizing, aggregation, and filtering _inside_ the mirai; not only does this make more of the work happen in parallel, but by returning the data in already-processed form, we can have much less data to transfer from the worker process back to the Shiny process. (For example, the data for May 31, 2018 weighs 75MB before optimization, and 8.8MB afterwards.)
581
582 Compare all three runs in the image below (the newly optimized version is labelled "async2"). The homepage load times have dropped further, and the calculation times are now dramatically faster than the sync code.
583
584 ![Faster response times using async served static assets](case-study-gantt-async2.png)
585
586 Looking at the "async2" graph, the leading (bottom-left) edge has the same shape as before, as that's simply the rate at which the load testing tool launches new sessions. But notice how much more closely the trailing (upper-right) edge matches the leading edge! It means that even as the number of active sessions ramped up, the amount of latency didn't get dramatically worse, unlike with the "sync" and "async" versions. And each of the individual blue rectangles in the "async2" are comparatively tiny, meaning that users never have to wait more than a dozen seconds at the most for plots to update.
587
588 This last plot shows the same data as above, but with the sessions aligned by start time. You can clearly see how the sessions are both shorter and less variable in "async2" compared to the others. I've added a yellow vertical line at the 10 second mark; if the page load (red/pink) has not completed at this point, it's likely that your visitor has left in disgust. While "async" does better than "sync", they both break through the 10 second mark early and often. In contrast, the "async2" version just barely peeks over the line three times.
589
590 ![Session timing aligned by start time displaying async2 is much better.](case-study-gantt-aligned.png)
591
592 To get a visceral sense for what it feels like to use the app under load, here's a video that shows what it's like to browse the app while the load test is running at its peak. The left side of the screen shows "sync", the right shows "async2". In both cases, I navigated to the app when session #40 was started.
593
594 <p class="embed-responsive embed-responsive-16by9">
595 <iframe class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/HsjdEZMnb0w?rel=0&amp;showinfo=0&amp;ecver=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
596 </p>
597
598 Take a look at the [code diff for async vs. async2](https://github.com/rstudio/cranwhales/compare/async...async2?diff=split). While the code has not changed very dramatically, it has lost a little elegance and maintainability: the code for each of the affected outputs now has one foot in the the render function and one foot in the mirai. If your app's total audience is a team of a hundred analysts and execs, you may choose to forgo the extra performance and stick with the original async (or even sync) code. But if you have serious scaling needs, the refactoring is probably a small price to pay.
599
600 Let's get real for a second, though. If this weren't an example app written for exposition purposes, but a real production app that was intended to scale to thousands of concurrent users across dozens of R processes, we wouldn't download and parse CSV files on the fly. Instead, we'd establish a proper [ETL procedure](https://solutions.posit.co/gallery/twitter-etl/) to run every night and put the results into a properly indexed database table, or RDS files with just the data we need. As I said [earlier](#improving-performance-and-scalability), a little precomputation and caching can make a huge difference!
601
602 Much of the remaining latency for the async2 branch is from ggplot2 plotting. [Sean's talk](https://posit.co/resources/) alluded to some upcoming plot caching features we're adding to Shiny, and I imagine they will have as dramatic an effect for this test as they did for Sean.
603
604 ## Summing up
605
606 With async programming, expensive computations and tasks no longer need to be the scalability killers that they once were for Shiny. Armed with this and other common techniques like precomputation, caching, and load balancing, it's possible to write responsive and scalable Shiny applications that can be safely deployed to thousands of concurrent users.