MCP HubMCP Hub
스킬 목록으로 돌아가기

optimize-shiny-performance

pjt222
업데이트됨 2 days ago
3 조회
17
2
17
GitHub에서 보기
메타general

정보

이 스킬은 캐싱, 비동기 작업, 반응형 흐름 제어 등의 기술을 활용하여 느리거나 응답이 없는 Shiny 애플리케이션의 프로파일링과 최적화를 지원합니다. 병목 현상을 식별하는 도구를 제공하며, 높은 동시 접속 부하를 견딜 수 있는 프로덕션 환경용 애플리케이션을 준비하는 데 이상적입니다. 주요 기능으로는 profvis, bindCache, memoise 및 ExtendedTask를 통한 장기 실행 계산 처리 등이 포함됩니다.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/optimize-shiny-performance

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Optimize Shiny Performance

Profile + opt: caching, async, reactive graph.

Use When

  • Slow / unresponsive interaction
  • Server resources exhausted under concurrent load
  • Specific ops bottleneck (data load, plot, compute)
  • Prep for prod w/ many users

In

  • Required: Path to Shiny app
  • Required: Perf problem desc (slow load, laggy, high mem)
  • Optional: Expected concurrent users
  • Optional: Server resources (RAM, CPU cores)
  • Optional: DB or API used?

Do

Step 1: Profile

# Profile with profvis
profvis::profvis({
  shiny::runApp("path/to/app", display.mode = "normal")
})

# Or profile specific operations
profvis::profvis({
  result <- expensive_computation(data)
})

ID top bottlenecks:

  1. Data load: initial fetch time?
  2. Reactive recalc: which reactives fire most?
  3. Render: which outputs slowest?
  4. External: DB queries, API, file I/O?

Reactive log for graph analysis:

# Enable reactive logging
options(shiny.reactlog = TRUE)
shiny::runApp("path/to/app")
# Press Ctrl+F3 in the browser to view the reactive graph

→ Clear ID of 2-3 biggest bottlenecks.

If err: profvis not detailed → wrap specific sections w/ profvis::profvis(). Reactlog overwhelming → focus one interaction at a time.

Step 2: Opt reactive graph

Cut unnecessary invalidations.

# BAD: Recomputes on ANY input change
output$plot <- renderPlot({
  data <- load_data()  # Runs every time
  filtered <- data[data$category == input$category, ]
  plot(filtered)
})

# GOOD: Isolate data loading from filtering
raw_data <- reactive({
  load_data()
}) |> bindCache()  # Cache the expensive part

filtered_data <- reactive({
  raw_data()[raw_data()$category == input$category, ]
})

output$plot <- renderPlot({
  plot(filtered_data())
})

isolate() to prevent unnecessary invalidations:

# Only recompute when the button is clicked, not on every input change
output$result <- renderText({
  input$compute  # Take dependency on button
  isolate({
    paste("N =", input$n, "Mean =", mean(rnorm(input$n)))
  })
})

debounce() + throttle() for high-freq inputs:

# Debounce text input — wait 500ms after user stops typing
search_text <- reactive(input$search) |> debounce(500)

# Throttle slider — update at most every 250ms
slider_value <- reactive(input$slider) |> throttle(250)

→ Reactive graph fires only necessary recalcs.

If err: removing dep breaks → use req() for explicit guards instead of implicit reactive deps.

Step 3: Caching

bindCache for outputs

output$plot <- renderPlot({
  create_expensive_plot(filtered_data())
}) |> bindCache(input$category, input$date_range)

output$table <- renderDT({
  expensive_query(input$filters)
}) |> bindCache(input$filters)

bindCache uses inputs as cache keys. Same inputs → cached result returned immediately.

memoise for fns

# Cache expensive function results
load_reference_data <- memoise::memoise(
  function(dataset_name) {
    readr::read_csv(paste0("data/", dataset_name, ".csv"))
  },
  cache = cachem::cache_disk("cache/", max_age = 3600)
)

App-level pre-compute

# In global.R or outside server function — computed once at app startup
reference_data <- readr::read_csv("data/reference.csv")
model <- readRDS("models/trained_model.rds")

server <- function(input, output, session) {
  # reference_data and model are available to all sessions
  # without reloading
}

→ Repeated ops use cache; response time drops.

If err: cache too big → set max_age / max_size. Stale → reduce max_age or cache-clear button. bindCache errors → ensure cache key inputs serializable.

Step 4: Async for long ops

ExtendedTask (Shiny ≥ 1.8.1):

server <- function(input, output, session) {
  # Define the extended task
  analysis_task <- ExtendedTask$new(function(data, params) {
    promises::future_promise({
      # This runs in a background process
      run_heavy_analysis(data, params)
    })
  }) |> bind_task_button("run_analysis")

  # Trigger the task
  observeEvent(input$run_analysis, {
    analysis_task$invoke(dataset(), input$params)
  })

  # Use the result
  output$result <- renderTable({
    analysis_task$result()
  })
}

For Shiny < 1.8.1, promises directly:

library(promises)
library(future)
plan(multisession, workers = 4)

server <- function(input, output, session) {
  result <- eventReactive(input$compute, {
    future_promise({
      Sys.sleep(5)  # Simulate long computation
      expensive_analysis(isolate(input$params))
    })
  })

  output$table <- renderTable({
    result()
  })
}

→ Long ops don't block UI; other users can interact during.

If err: future_promise errors → check plan(multisession) set. Vars unavailable in future → pass explicitly (separate R process).

Step 5: Opt rendering

Cut render overhead.

# Use plotly for interactive plots instead of re-rendering
output$plot <- plotly::renderPlotly({
  plotly::plot_ly(filtered_data(), x = ~x, y = ~y, type = "scatter")
})

# Use server-side DT for large tables
output$table <- DT::renderDataTable({
  DT::datatable(large_data(), server = TRUE, options = list(
    pageLength = 25,
    processing = TRUE
  ))
})

# Conditional UI to avoid rendering hidden elements
output$details <- renderUI({
  req(input$show_details)
  expensive_details_ui()
})

→ Render faster, no UI block.

If err: plotly slow w/ big data → toWebGL() or downsample before plot.

Step 6: Validate

# Before/after benchmarking
system.time({
  shiny::testServer(myModuleServer, args = list(...), {
    session$setInputs(category = "A")
    session$flushReact()
  })
})

# Load testing with shinyloadtest
shinyloadtest::record_session("http://localhost:3838")
shinyloadtest::shinycannon(
  "recording.log",
  "http://localhost:3838",
  workers = 10,
  loaded_duration_minutes = 5
)
shinyloadtest::shinyloadtest_report("recording.log")

→ Measurable improvement in response times / concurrent capacity.

If err: no improvement → re-profile for next bottleneck. Iterative — fix biggest first, re-measure.

Check

  • Profiling IDs specific bottlenecks (not guessing)
  • Reactive graph: no unnecessary invalidation chains
  • Expensive ops use cache (bindCache/memoise)
  • Long ops use async (ExtendedTask/promises)
  • High-freq inputs use debounce/throttle
  • Big data → server-side
  • Improvement measurable (before/after)

Traps

  • Premature opt: profile first. Bottleneck rarely where you think
  • Cache invalidation bugs: stale data → cache key missing inputs. Add deps to bindCache()
  • Future variable scoping: future_promise = separate process. Globals, DB conns, reactive vals → capture explicitly
  • Reactive spaghetti: too complex graph → architectural refactor (modules), not just cache
  • Over-caching: caching all = waste mem. Only expensive ops w/ repeated input patterns

  • build-shiny-module — modular arch for maintainable reactive code
  • scaffold-shiny-app — pick right framework from start
  • deploy-shiny-app — deploy optimized w/ proper resources
  • test-shiny-app — perf regression tests

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman-ultra/skills/optimize-shiny-performance
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기