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

perf(core): update mongodb default connection settings #4646

Merged
merged 5 commits into from
Nov 6, 2024
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
1 change: 1 addition & 0 deletions core/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
"prom-client": "^15.1.3",
"rate-limiter-flexible": "^5.0.1",
"redlock": "^5.0.0-beta.2",
"snappy": "^7.2.2",
"svix": "1.37.0",
"tiny-secp256k1": "^2.2.3",
"twilio": "^5.3.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const updateWalletInvoiceWithPaymentRequest = wrapAsyncToRunInSpan({
},
})

setupMongoConnection(false)
setupMongoConnection()
.then(async (mongoose) => {
await Promise.all(lndsConnect.map((lndParams) => isUp(lndParams)))
await main()
Expand Down
2 changes: 1 addition & 1 deletion core/api/src/debug/clean-pending-payments-for-dead-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const main = async (): Promise<true | ApplicationError> => {
return true
}

setupMongoConnection(false)
setupMongoConnection()
.then(async (mongoose) => {
await Promise.all(lndsConnect.map((lndParams) => isUp(lndParams)))
await main()
Expand Down
2 changes: 1 addition & 1 deletion core/api/src/debug/migrate-ln-payments-listpayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ const getFirstIndex = async (pubkey: Pubkey): Promise<number | ApplicationError>
: parseInt(indexMatch) + 1
}

setupMongoConnection(false)
setupMongoConnection()
.then(async (mongoose) => {
await Promise.all(lndsConnect.map((lndParams) => isUp(lndParams)))
await main()
Expand Down
2 changes: 1 addition & 1 deletion core/api/src/debug/migrate-ln-payments-trackpaymentsv2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ const migrateLnPayment = async (
},
)

setupMongoConnection(false)
setupMongoConnection()
.then(async (mongoose) => {
await Promise.all(lndsConnect.map((lndParams) => isUp(lndParams)))
await main()
Expand Down
5 changes: 4 additions & 1 deletion core/api/src/servers/exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,10 @@ const main = async () => {
activateLndHealthCheck()
}

setupMongoConnection()
setupMongoConnection({
syncIndexes: false,
options: { readPreference: "secondaryPreferred", socketTimeoutMS: 120000 },
})
.then(() => main())
.catch((err) => logger.error(err))

Expand Down
2 changes: 1 addition & 1 deletion core/api/src/servers/graphql-main-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { activateLndHealthCheck } from "@/services/lnd/health"
import { baseLogger } from "@/services/logger"
import { setupMongoConnection } from "@/services/mongodb"

setupMongoConnection(true)
setupMongoConnection({ syncIndexes: true })
.then(async () => {
activateLndHealthCheck()

Expand Down
4 changes: 1 addition & 3 deletions core/api/src/services/ledger/admin-legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ const getWalletBalance = async (account: string, query = {}) => {

const balancePromise = (async () => {
try {
const { balance } = await MainBookAdmin.balance(params, {
readPreference: "secondaryPreferred",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

now it is not required because readPreference is setup at server level

})
const { balance } = await MainBookAdmin.balance(params)
return balance
} finally {
inProgressQueries.delete(inProgressKey)
Expand Down
18 changes: 6 additions & 12 deletions core/api/src/services/ledger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,12 +312,9 @@ export const LedgerService = (): ILedgerService => {
): Promise<Satoshis | LedgerError> => {
const liabilitiesWalletId = toLiabilitiesWalletId(walletId)
try {
const { balance } = await MainBook.balance(
{
account: liabilitiesWalletId,
},
{ readPreference: "primaryPreferred" },
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

now it is not required because readPreference default value is primaryPreferred

)
const { balance } = await MainBook.balance({
account: liabilitiesWalletId,
})
if (balance < 0) {
const dealerUsdWalletId = await caching.getDealerUsdWalletId()
const dealerBtcWalletId = await caching.getDealerBtcWalletId()
Expand All @@ -343,12 +340,9 @@ export const LedgerService = (): ILedgerService => {
): Promise<BalanceAmount<S> | LedgerError> => {
const liabilitiesWalletId = toLiabilitiesWalletId(walletDescriptor.id)
try {
const { balance } = await MainBook.balance(
{
account: liabilitiesWalletId,
},
{ readPreference: "primaryPreferred" },
)
const { balance } = await MainBook.balance({
account: liabilitiesWalletId,
})
if (balance < 0) {
const dealerWalletIds = Object.values(await caching.getDealerWalletIds())

Expand Down
36 changes: 34 additions & 2 deletions core/api/src/services/mongodb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,36 @@ import { WalletCurrency } from "@/domain/shared"
import { lazyLoadLedgerAdmin } from "@/services/ledger"
import { WalletsRepository } from "@/services/mongoose"

type SetupMongoConnectionArgs = {
syncIndexes: boolean
options?: mongoose.ConnectOptions
}

const DEFAULT_MONGODB_OPTIONS: mongoose.ConnectOptions = {
autoIndex: false,
compressors: ["snappy", "zlib"],

maxPoolSize: 100,
minPoolSize: 15,
maxConnecting: 5, // Maximum number of concurrent connection attempts

socketTimeoutMS: 60000, // Close sockets after 60 seconds of inactivity
connectTimeoutMS: 15000, // Give up initial connection after 15 seconds
serverSelectionTimeoutMS: 15000, // Keep trying to send operations for 15 seconds

retryWrites: true,
writeConcern: {
w: "majority", // Wait for majority acknowledgment
j: true, // Wait for journal commit
wtimeout: 10000, // Write timeout
},

retryReads: true,
maxStalenessSeconds: 90,
readPreference: "primaryPreferred", // Prefer primary but allow secondary reads
readConcern: { level: "majority" }, // Read from majority-committed data
} as const
Comment on lines +25 to +48
Copy link
Collaborator

Choose a reason for hiding this comment

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

Compared the defaults there is compression introduced and more connections with bigger pool sizes, these settings expected to increase the performance.
Can you link the baseline you are comparing to?

Then in writeConcern and readConcern these settings should improve the consistency, hopefully not with too much tradeoff in performance.


export const ledgerAdmin = lazyLoadLedgerAdmin({
bankOwnerWalletResolver: async () => {
const result = await Account.findOne({ role: "bankowner" }, { defaultWalletId: 1 })
Expand Down Expand Up @@ -63,9 +93,11 @@ export const ledgerAdmin = lazyLoadLedgerAdmin({
// TODO add an event listenever if we got disconnecter from MongoDb
// after a first successful connection

export const setupMongoConnection = async (syncIndexes = false) => {
export const setupMongoConnection = async (
{ syncIndexes, options }: SetupMongoConnectionArgs = { syncIndexes: false },
) => {
try {
await mongoose.connect(MONGODB_CON, { autoIndex: false })
await mongoose.connect(MONGODB_CON, { ...DEFAULT_MONGODB_OPTIONS, ...options })
} catch (err) {
baseLogger.fatal(`error connecting to mongodb`)
throw err
Expand Down
2 changes: 1 addition & 1 deletion core/api/test/integration/jest.setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jest.mock("@/services/lnd/auth", () => {
jest.mock("@/app/prices/get-current-price", () => require("test/mocks/get-current-price"))

beforeAll(async () => {
mongoose = await setupMongoConnection(true)
mongoose = await setupMongoConnection({ syncIndexes: true })
})

afterAll(async () => {
Expand Down
Loading
Loading