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

Improve last token native price sql query #3269

Merged
merged 6 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions crates/orderbook/src/database/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,39 +493,48 @@ impl Postgres {
}

pub async fn token_metadata(&self, token: &H160) -> Result<TokenMetadata> {
let timer = super::Metrics::get()
.database_queries
.with_label_values(&["token_first_trade_block"])
.start_timer();

let (first_trade_block, native_price) = tokio::try_join!(
async {
let (first_trade_block, native_price): (Option<u32>, Option<U256>) = tokio::try_join!(
self.execute_instrumented("token_first_trade_block", async {
let mut ex = self.pool.acquire().await?;
database::trades::token_first_trade_block(&mut ex, ByteArray(token.0))
.await
.map_err(anyhow::Error::from)?
.map(u32::try_from)
.transpose()
.map_err(anyhow::Error::from)
},
async {
}),
self.execute_instrumented("fetch_latest_token_price", async {
let mut ex = self.pool.acquire().await?;
Ok::<Option<U256>, anyhow::Error>(
Ok(
database::auction_prices::fetch_latest_token_price(&mut ex, ByteArray(token.0))
.await
.map_err(anyhow::Error::from)?
.and_then(|price| big_decimal_to_u256(&price)),
)
}
})
)?;

timer.stop_and_record();

Ok(TokenMetadata {
first_trade_block,
native_price,
})
}

async fn execute_instrumented<F, T>(&self, label: &str, f: F) -> Result<T>
where
F: std::future::Future<Output = Result<T>>,
{
let timer = super::Metrics::get()
.database_queries
.with_label_values(&[label])
.start_timer();

let result = f.await?;

timer.observe_duration();

Ok(result)
}
}

#[async_trait]
Expand Down
2 changes: 2 additions & 0 deletions database/sql/V079__auction_prices_token_index.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Create index to improve `fetch_latest_token_price` query performance.
CREATE INDEX auction_prices_token_auction_id_idx ON auction_prices (token, auction_id DESC);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving a reminder to myself that here is another performance reason why we will probably have to keep auction_prices table, and erase auction prices from competition_auctions. (there are a few more places in the code)

Loading