Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-blocking Database Queries within app$get() #41

Closed
m-saenger opened this issue Jun 15, 2021 · 3 comments
Closed

Non-blocking Database Queries within app$get() #41

m-saenger opened this issue Jun 15, 2021 · 3 comments

Comments

@m-saenger
Copy link

m-saenger commented Jun 15, 2021

Project:
The goal is an API which queries a database. Results set length varies a lot and so does the response time. In order to avoid blocking of fast queries by slow ones the API should by async.

Problem:
future does not allow for external pointers (such as DB connections, pool connections, etc.), thus I had to open a new DB connection (within future) for every request which slows down response time significantly

I am looking for a solution based on this example with a non-blocking query_db() functionality within the future.

Any help would be greatly appreciated!

library(future)
library(ambiorix)

plan(multisession)

app <- Ambiorix$new()

app$get("/async", function(req, res){
  future({
    dat <- query_db()
    res$send(dat)
  })
})
app$start()
@m-saenger
Copy link
Author

m-saenger commented Jan 22, 2022

Finally I used the psql command line tool as a workaround to access the Postgres DB from within a future. There is some overhead obviously (open/close connection for each request), but speed is excellent and memory usage acceptable. data.table::fread allows to read psqloutput directly into a data.table (via cmd argument). Working example: https://myweather.ch/map

Minimal example:

library(future)
library(ambiorix)
library(data.table)
plan(multisession)

app <- Ambiorix$new()

app$get("/async", function(req, res){
  future({
    q <- "SELECT something FROM somewhere;"
    cmd <- sprintf("psql -h somehost -d somedb -U someuser -w -c %s -AF,", shQuote(q))
    dat <- data.table::fread(cmd = cmd))
    # Fix column types if necessary
    res$send(dat)
  })
})
app$start()

@JohnCoene
Copy link
Member

@m-saenger I'm sorry I never came back to you on this issue. I've setup my company last year and it left me very little time for all open-source projects.

Has this been resolved? Have you found a solution?

@m-saenger
Copy link
Author

No worries. I found a workaround and closed this issues a couple of days ago. See #41 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants