Key Data Dependency Types and Usage [Deprecated]
There are situations when you want to keep a relationship among related cache data. For example, if an order depends on a product that is no longer available, the cache must remove all its dependents, as well. Here you can use the Key Dependency to maintain this relationship. Essentially, a Key Dependency creates a dependency relationship between cached items.
Note
The dependent item is removed in case of two types of modifications in the master key:
In NCache, dependent cache items and those on whom others depend are aware of this relationship. When the cache removes such an item on which other cache items depend, it will also remove all its dependents. However, vice versa is not possible. For example, Products will not be removed, if any of the Orders are updated or removed.
Key(s) can have two types of dependencies:
Multilevel Dependency
A cache item can depend on any number of other items in the cache resulting in the formation of a chain. The relationship, in this case, will be a 1:1 relationship. For instance, if there are three data sets in a cache, i.e., Products, Orders, and OrderDetails. An order placed on a particular Product, the key of the OrderDetails depends on the key of the Orders. Similarly, the key of the Orders depends on the key of the Products. This means that if the Products are deleted, the Orders and the OrderDetails are also deleted. The following diagram depicts this scenario visually.

Multiple Dependency
A single item can depend on more than one item in the cache. Similarly, that item may depend on multiple items. This may result in a "1:n" relationship between the items. For example, in a cache, if an Order is placed by a Customer which contains a Product, the Order depends on the Customer and Product. Similarly, the OrderDetails depend on the Orders. The following diagram depicts the whole scenario visually.

If the Customer is deleted, Orders and OrderDetails get deleted. Similarly, if the Product is deleted, Orders and OrderDetails get deleted.
Note
You can only specify existing keys in a cache for Key Dependency. A non-existent key specified for Key Dependency will result in an OperationFailedException. Whereas an object can be considered dependent on another key at the time of addition.
Prerequisites
- Create a new Console Application.
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Professional:
Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
- Make sure that the data being added is serializable.
- Add NCache References by locating
%NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
- Include the
Alachisoft.NCache.Runtime.Dependencies namespace in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
Add CacheItem to Cache with Key Data Dependency
The CacheItem is a custom class provided by NCache that can be used to add data to the cache and lets you set additional metadata associated with an object of this class. This metadata defines the item properties like dependencies, expirations, and more. The Add method adds a new item in the cache, whereas the Insert method adds a new item with dependency. If this CacheItem already exists in the cache, it overwrites its properties.
Important
Note that this API also specifies CacheItem priority for Eviction and Expiration, where the value for that parameter is passed as Default.
The following example adds a CacheItem order to the cache using the Insert method, which is dependent on the customer in the cache, which means as soon as the customer is updated or deleted, the order of the customer is already deleted from the cache.
// Precondition: Cache is already connected
// Get customer from database
Customer customer = FetchCustomerFromDB("ALFKI");
// Add customer in cache
cache.Add(customer.CustomerID, customer);
// Get order from customer
Order order = new Order
{
OrderID = 10248,
OrderDate = DateTime.Now,
ShipAddress = "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
bool isOrderSaved = SaveOrderToDB(order);
// Generate order Id
string orderKey = $"Order:{order.OrderID}";
if (isOrderSaved)
{
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(customer.CustomerID);
// Create CacheItem to your desired object
CacheItem cacheItem = new CacheItem(order);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Add order in cache
cache.Add(orderKey, cacheItem);
}
// Create order detail for the order
OrderDetail orderDetail = new OrderDetail
{
OrderID = order.OrderID,
UnitPrice = 200,
Discount = 25.5F,
Quantity = 10,
};
// Save order detail to database
bool isOrderDetailSaved = SaveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
string orderDetailId = $"OrderDetail: {orderDetail.OrderID}";
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Apply dependency on order
cacheItem.Dependency = dependency;
// Insert order detail in cache with dependency
cache.Add(orderDetailId, cacheItem);
}
// Precondition: Cache is already connected
// Get customer from database
Customer customer = fetchCustomerFromDB("ALFKI");
// Add customer in cache
cache.add(customer.getCustomerID(), customer);
// Get order from customer
Order order = new Order(10248, LocalDateTime.now(), "Carrera 22 con Ave. Carlos Soublette #8-35");
// Save order to database
boolean isOrderSaved = saveOrderToDB(order);
// Generate order Id
String orderKey = "Order:" + order.getOrderID();
if (isOrderSaved)
{
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(order);
// Generate an instance of Key Dependency
cacheItem.setDependency(new KeyDependency(customer.getCustomerID()));
// Insert order in cache
cache.insert(orderKey, cacheItem);
}
// Create order detail for the order
OrderDetail orderDetail = new OrderDetail(10248, 200, 25.5F, 10);
// Save order detail to database
boolean isOrderDetailSaved = SaveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
String orderDetailId = "OrderDetail:" + orderDetail.getOrderID();
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Apply dependency on order
cacheItem.setDependency(dependency);
// Insert order detail in cache with dependency
cache.insert(orderDetailId, cacheItem);
}
# Precondition: Cache is already connected
# Get customer from database
customer = fetch_customer_from_db("ALFKI")
customer_key = f"Customer:{customer.get_customer_id()}"
# Add customer in cache
cache.add(customer_key, customer)
# Get order from customer
order = Order(
order_id=10248,
customer_id=customer.get_customer_id(),
order_date=datetime.now(),
ship_address="Carrera 22 con Ave. Carlos Soublette #8-35",
)
# Save order to database
is_order_saved = save_order_to_db(order)
# Generate order Id
order_key = f"Order:{order.get_order_id()}"
if is_order_saved:
# Generate an instance of Key Dependency
dependency = KeyDependency(customer_key)
# Create CacheItem with your desired object
cache_item = CacheItem(order)
# Add Key Dependency to order
cache_item.set_dependency(dependency)
# Add order in cache
cache.add(order_key, cache_item)
# Create order detail for the order
order_detail = OrderDetail(
order_id=order.get_order_id(),
unit_price=200,
discount=25.5,
quantity=10
)
# Save order detail to database
is_order_detail_saved = save_order_detail_to_db(order_detail)
if is_order_detail_saved:
# Generate order detail Id
order_detail_key = f"OrderDetail:{order_detail.get_order_id()}"
# Generate an instance of Key Dependency
dependency = KeyDependency(order_key)
# Create CacheItem with your desired object
cache_item = CacheItem(order_detail)
# Apply dependency on order
cache_item.set_dependency(dependency)
# Insert order detail in cache with dependency
cache.add(order_detail_key, cache_item)
// This is an async method
// Precondition: Cache is already connected
// Get customer from database
const customer = await fetchCustomerFromDB("ALFKI");
// Add customer in cache
const customerKey = `Customer:${customer.customerID}`;
const customerItem = new CacheItem(JSON.stringify(customer));
await cache.add(customerKey, customerItem);
// Get order from customer
const order =
{
orderId: 10248,
orderDate: new Date().toISOString(),
shipAddress: "Carrera 22 con Ave. Carlos Soublette #8-35",
customerId: customer.customerID
};
// Save order to DB first
const isOrderSaved = await saveOrderToDB(order);
// Generate order Id
const orderKey = `Order:${order.orderId}`;
// Save order to database
if (isOrderSaved)
{
// Create CacheItem with your desired object
const orderItem = new CacheItem(JSON.stringify(order));
// Generate an instance of Key Dependency
const orderDependency = new KeyDependency([customerKey]);
// Add Key Dependency to order
orderItem.setDependency(orderDependency);
// Add order in cache
await cache.add(orderKey, orderItem);
}
// Create order detail for the order
const orderDetail =
{
orderId: order.orderId,
unitPrice: 200,
discount: 25.5,
quantity: 10
};
// Save order detail to database
const isOrderDetailSaved = await saveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
const orderDetailKey = `OrderDetail:${orderDetail.orderId}`;
// Create CacheItem with your desired object
const orderDetailItem = new CacheItem(JSON.stringify(orderDetail));
// Generate an instance of Key Dependency
const detailDependency = new KeyDependency([orderKey]);
// Apply dependency on order
orderDetailItem.setDependency(detailDependency);
// Add order detail in cache with dependency
await cache.add(orderDetailKey, orderDetailItem);
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Get customer from database
Customer customer = FetchCustomerFromDB("ALFKI");
// Add customer to cache
cache.Add(customer.CustomerID, customer);
// Get order from customer
Order order = new Order
{
OrderID = 10248,
OrderDate = DateTime.Now,
ShipAddress = "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
bool orderSaved = SaveOrderToDB(order);
// Generate order Id
string orderKey = "Order:" + order.OrderID;
// Save Order
if (orderSaved)
{
cache.Add(orderKey, order, new KeyDependency(customer.CustomerID), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
}
// Create OrderDetail
OrderDetail orderDetail = new OrderDetail
{
OrderID = order.OrderID,
UnitPrice = 200,
Discount = 25.5F,
Quantity = 10
};
// Save order's detail to database
bool detailSaved = SaveOrderDetailToDB(orderDetail);
// Generate order detail Id
string detailKey = "OrderDetail:" + orderDetail.OrderID;
if (detailSaved)
{
cache.Add(detailKey, orderDetail, new KeyDependency(orderKey), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Key Dependency on Multiple Keys
You can also add Key Dependency to an item which is dependent on multiple keys. This way a single item can be dependent on multiple items using the Add or Insert method. The Add method adds a new item in the cache whereas the Insert method adds a new item with dependency, and if the item already exists in the cache it overwrites its properties. The following example demonstrates this.
// Precondition: Cache is already connected
// Get customer from database
Customer customer = FetchCustomerFromDB();
// Get product from database
Product product = FetchProductFromDB();
// Add customer in cache
cache.Add(customer.CustomerID, customer);
// Add product to cache
string productId = $"Product: {product.ProductID}";
cache.Add(productId, product);
// Get order from customer
Order order = new Order
{
OrderID = 10248,
OrderDate = DateTime.Now,
ShipAddress = "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
bool isOrderSaved = SaveOrderToDB(order);
// Generate order Id
string orderKey = $"Order: {order.OrderID}";
if (isOrderSaved)
{
string[] dependencyKeys = { productId, customer.CustomerID };
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(dependencyKeys);
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(order);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Insert order into cache with dependencies
cache.Insert(orderKey, cacheItem);
}
// Create order detail
OrderDetail orderDetail = new OrderDetail
{
OrderID = order.OrderID,
UnitPrice = 200,
Discount = 25.5F,
Quantity = 10,
};
// Save order's detail to database
bool isOrderDetailSaved = SaveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
string orderDetailId = $"OrderDetail: {orderDetail.OrderID}";
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Insert order detail into cache with dependencies
cache.Insert(orderDetailId, cacheItem);
}
// Precondition: Cache is already connected
// Get customer from database
Customer customer = Customer.fetchCustomerFromDB("Customer:ALFKI");
// Get product from database
Product product = Product.fetchProductFromDB("Product:1001");
// Add customer in cache
cache.add(customer.getCustomerID(), customer);
// Add product to cache
String productId = product.getProductID();
cache.add(productId, product);
// Get order from customer
Order order = new Order(10248, LocalDateTime.now(), "Carrera 22 con Ave. Carlos Soublette #8-35");
// Save order to database
boolean isOrderSaved = saveOrderToDB(order);
// Generate order Id
String orderKey = "Order:" + order.getOrderID();
if (isOrderSaved)
{
List<String> dependencyKeys = Arrays.asList(productId, customer.getCustomerID());
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(dependencyKeys);
// Create CacheItem to with your desired object
CacheItem cacheItem = new CacheItem(order);
// Add Key Dependency to order
cacheItem.setDependency(dependency);
// Insert order into cache with dependencies
cache.insert(orderKey, cacheItem);
}
// Create order detail
OrderDetail orderDetail = new OrderDetail(10248, 200, 25.5F, 10);
// Save order detail to database
boolean isOrderDetailSaved = saveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
String orderDetailId = "OrderDetail:" + orderDetail.getOrderID();
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Add Key Dependency to order
cacheItem.setDependency(dependency);
// Insert order detail into cache with dependencies
cache.insert(orderDetailId, cacheItem);
}
# Precondition: Cache is already connected
# Get customer from database
customer = fetch_customer_from_db("ALFKI")
# Get product from database
product = fetch_product_from_db("1001")
# Add customer in cache
customer_key = f"Customer:{customer.get_customer_id()}"
cache.add(customer_key, customer)
# Add product to cache
product_key = f"Product:{product.get_product_id()}"
cache.add(product_key, product)
# Get order from customer
order = Order(
order_id=10248,
customer_id=customer.get_customer_id(),
order_date=datetime.now(),
ship_address="Carrera 22 con Ave. Carlos Soublette #8-35"
)
# Save order to database
is_order_saved = save_order_to_db(order)
# Generate order Id
order_key = f"Order:{order.get_order_id()}"
if is_order_saved:
dependency_keys = [product_key, customer_key]
# Generate an instance of Key Dependency
dependency = KeyDependency(dependency_keys)
# Create CacheItem with your desired object
cache_item = CacheItem(order)
# Add Key Dependency to order
cache_item.set_dependency(dependency)
# Insert order into cache with dependencies
cache.insert(order_key, cache_item)
# Create order detail
order_detail = OrderDetail(
order_id=order.get_order_id(),
unit_price=200,
discount=25.5,
quantity=10
)
# Save order's detail to database
is_order_detail_saved = save_order_detail_to_db(order_detail)
if is_order_detail_saved:
# Generate order detail Id
order_detail_key = f"OrderDetail:{order_detail.get_order_id()}"
# Generate an instance of Key Dependency
dependency = KeyDependency(order_key)
# Create CacheItem with your desired object
cache_item = CacheItem(order_detail)
# Add Key Dependency to order
cache_item.set_dependency(dependency)
# Insert order detail into cache with dependencies
cache.insert(order_detail_key, cache_item)
// Precondition: Cache is already connected
// Get customer from database
const customer = await fetchCustomerFromDB();
// Get product from database
const product = await fetchProductFromDB();
// Add customer in cache
const customerKey = customer.customerID;
const customerItem = new CacheItem(JSON.stringify(customer));
await cache.add(customerKey, customerItem);
console.log(`✅ Customer ${customer.customerID} added to cache`);
// Add product to cache
const productKey = `Product:${product.productID}`;
const productItem = new CacheItem(JSON.stringify(product));
await cache.add(productKey, productItem);
console.log(`✅ Product ${product.productID} added to cache`);
// Get order from customer
const order = {
orderId: 10248,
orderDate: new Date().toISOString(),
shipAddress: "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
const isOrderSaved = await saveOrderToDB(order);
// Generate order Id
const orderKey = `Order:${order.orderId}`;
if (isOrderSaved) {
// Generate an instance of Key Dependency
const dependency = new KeyDependency([productKey, customerKey]);
// Create CacheItem with your desired object
const orderItem = new CacheItem(JSON.stringify(order));
// Add Key Dependency to order
orderItem.setDependency(dependency);
// Insert order into cache with dependencies
await cache.insert(orderKey, orderItem);
}
// Create order detail
const orderDetail = {
orderId: order.orderId,
unitPrice: 200,
discount: 25.5,
quantity: 10
};
// Save order's detail to database
const isOrderDetailSaved = await saveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved) {
// Generate order Id
const orderDetailKey = `OrderDetail:${orderDetail.orderId}`;
// Generate an instance of Key Dependency
const detailDependency = new KeyDependency([orderKey]);
// Create CacheItem with your desired object
const orderDetailItem = new CacheItem(JSON.stringify(orderDetail));
// Add Key Dependency to order
orderDetailItem.setDependency(detailDependency);
// Insert order detail into cache with dependencies
await cache.insert(orderDetailKey, orderDetailItem);
}
Add Key Dependency to Existing Cache Item
NCache lets you add a Key Dependency to an item already present in the cache, without re-inserting it into the cache. This process occurs through the CacheItemAttribute class which has the property of Dependency to be set against CacheItem. The attribute is then set against the existing key of the item, using the UpdateAttributes method of the Cache class.
The following example shows that an order and a customer are already present in the cache without dependency, and dependency is added using UpdateAttributes such that if the customer is updated or removed in the cache, the order is automatically removed.
// Precondition: Cache is already connected
string orderId = "Order:10248";
string ProductId = "Product:8899";
// Create a Key Dependency
CacheDependency dependency = new KeyDependency(ProductId);
// Create a cache item attribute
CacheItemAttributes itemAttribute = new CacheItemAttributes();
// Set dependency to cache item attribute
itemAttribute.Dependency = dependency;
// Update attribute in cache
cache.UpdateAttributes(orderId, itemAttribute);
// Precondition: Cache is already connected
String orderId = "Order:10248";
String productId = "Product:1001";
// Create a Key Dependency
CacheDependency dependency = new KeyDependency(productId);
// Create a cache item attribute
CacheItemAttributes itemAttributes = new CacheItemAttributes();
// Set dependency to cache item attribute
itemAttributes.setDependency(dependency);
// Update attribute in cache
cache.updateAttributes(orderId, itemAttributes);
# Precondition: Cache is already connected
order_id = "Order:10248"
product_id = "Product:8899"
# Create a Key Dependency
dependency = KeyDependency([product_id])
# Create a cache item attribute
attributes = CacheItemAttributes()
# Set dependency to cache item attribute
attributes.set_dependency(dependency)
# Update attribute in cache
cache.update_attributes(order_id, attributes)
// Precondition: Cache is already connected
// This is an async method
// Precondition: both the items already exist in the cache
const orderId = "Order:10248";
const productId = "Product:8899";
// create Key Dependency where order is dependent on customer
const dependency = new KeyDependency([productId]);
// Create a CacheItemAttributes for dependency
const itemAttributes = new CacheItemAttributes();
// Set dependency to cache item attribute
itemAttributes.setDependency(dependency);
// Update attribute in cache
const result = await cache.updateAttributes(orderId, itemAttributes);
Additional Resources
NCache provides a sample application for Key Dependency on GitHub.
See also
.NET: Alachisoft.NCache.Runtime.Dependencies namespace.
Java: com.alachisoft.ncache.runtime.dependencies namespace.
Python: ncache.runtime.dependencies class.
Node.js: Key Dependency class.