My Shiny app is slow: what to fix first
Every click takes seconds and people give up. Most slow Shiny apps have the same three problems: reading data again for every visitor, redoing the same slow work, and reacting to every key press. Fix those first.
What we need
- R 4.1 or newer
- shiny 1.6 or newer
- An app that feels slow
Fix 1: read the data once, outside the server
Code inside server() runs again for every visitor. Read big files once, at the top of the app, so everyone shares them.
library(shiny)
# Read once, when the app starts, not inside server()
requests <- data.frame(
borough = sample(c("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island"), 1e5, TRUE),
days = rexp(1e5, 1 / 5)
)Fix 2: remember slow results with bindCache()
If many people pick the same choice, work it out once and reuse it. bindCache() keeps the answer for each choice.
ui <- fluidPage(
selectInput("boro", "Borough", unique(requests$borough)),
plotOutput("hist")
)
server <- function(input, output, session) {
output$hist <- renderPlot({
hist(requests$days[requests$borough == input$boro], main = input$boro)
}) |>
bindCache(input$boro)
}Fix 3: wait for the reader to finish typing
A search box reacts to every key press. debounce() waits until the typing stops for a moment, here half a second.
server <- function(input, output, session) {
word <- reactive(input$search) |> debounce(500)
output$n <- renderText({
sum(grepl(word(), requests$borough, ignore.case = TRUE))
})
}Find what is slow before guessing
The profvis package records where the time goes while we click around. Fix the biggest bar first.
library(profvis)
profvis(runApp(shinyApp(ui, server)))Kitchen tip: the habit that prevents this
Measure first with profvis, then fix the slowest part. Moving data loading out of server() is the most common big win.
Three common mix-ups
- Putting read.csv() inside renderPlot(), so the file is read on every click.
- Caching an output that depends on something we did not list in bindCache(), so people see an old answer.
- Drawing hundreds of thousands of points in one chart. Summarize first, then draw.
Quick check
Our app reads a 200 MB file inside server(). Ten people open it. How many times is the file read?
- read data outside server()
- bindCache() for repeated work
- debounce() for typing
- profvis() to find the slow part
Keep the recipe card
A one-picture summary to pin next to a screen or send to a friend who is stuck on the same thing.
Trying this on other data? Check the row counts and results before and after each step. Package versions change, so if something here works differently, please tell us. Every output on this page comes from running the code above in R; please cross-check before relying on it for our work.