info:To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
---
# Loose foreign keys
## Problem statement
In relational databases (including PostgreSQL), foreign keys provide a way to link
two database tables together, and ensure data-consistency between them. In GitLab,
[foreign keys](../foreign_keys.md) are vital part of the database design process.
Most of our database tables have foreign keys.
With the ongoing database [decomposition work](https://gitlab.com/groups/gitlab-org/-/epics/6168),
linked records might be present on two different database servers. Ensuring data consistency
between two databases is not possible with standard PostgreSQL foreign keys. PostgreSQL
does not support foreign keys operating within a single database server, defining
a link between two database tables in two different database servers over the network.
Example:
- Database "Main": `projects` table
- Database "CI": `ci_pipelines` table
A project can have many pipelines. When a project is deleted, the associated `ci_pipeline` (via the
`project_id` column) records must be also deleted.
With a multi-database setup, this cannot be achieved with foreign keys.
## Asynchronous approach
Our preferred approach to this problem is eventual consistency. With the loose foreign keys
feature, we can configure delayed association cleanup without negatively affecting the
application performance.
### How it works
In the previous example, a record in the `projects` table can have multiple `ci_pipeline`
records. To keep the cleanup process separate from the actual parent record deletion,
we can:
1. Create a `DELETE` trigger on the `projects` table.
Record the deletions in a separate table (`deleted_records`).
1. A job checks the `deleted_records` table every 5 minutes.
1. For each record in the table, delete the associated `ci_pipelines` records
using the `project_id` column.
NOTE:
For this procedure to work, we must register which tables to clean up asynchronously.
## Example migration and configuration
### Configure the model
First, tell the application that the `projects` table has a new loose foreign key.
You can do this in the `Project` model:
```ruby
classProject<ApplicationRecord
# ...
includeLooseForeignKey
loose_foreign_key:ci_pipelines,:project_id,on_delete: :async_delete# or async_nullify
# ...
end
```
This instruction ensures the asynchronous cleanup process knows about the association, and the
how to do the cleanup. In this case, the associated `ci_pipelines` records are deleted.
### Track record changes
To know about deletions in the `projects` table, configure a `DELETE` trigger using a database
migration (post-migration). The trigger needs to be configured only once. If the model already has
at least one `loose_foreign_key` definition, then this step can be skipped: